Generate letters to represent number using ruby?

后端 未结 8 1715
你的背包
你的背包 2020-12-24 15:00

I would like to generate a sequence of letters i.e. \"A\", \"DE\" \"GJE\", etc. that correspond to a number. The first 26 are pretty easy so 3 returns \"C\", 26 returns \"Z\

相关标签:
8条回答
  • 2020-12-24 15:22

    Here is a short performant recursion based solution

    class Numeric
      # 'z' is placed in the begining of the array because 26 % 26 is 0 not 26
      Alph = ['z'] + ("a".."y").to_a
    
      def to_alph
    
        # if self is 0 or negative return a blank string.
        # this is also used to end the recursive chain of to_alph calls
        # so don't replace this with raising an error or returning anything else
    
        return '' if self < 1
    
        # (otherwise) return two concatenated strings:
        # the right side is the letter for self modules 26
        # the left side is comprised of:
        #  1. minus one, because this is not a zero-based numbering system.
        #     therefore, round numbers (26, 52...) should return one digit 'z'
        #     instead of two digits 'aa' or 'ba'.
        #  2. divide by 26 and call to_alph on that.
        #     this repeats recursively for every digit of the final string,
        #     plus once more that will return '' to end the recursion chain.
    
        return ((self - 1) / 26).to_alph + Alph[self % 26]
      end
    end
    
    0 讨论(0)
  • 2020-12-24 15:29

    I liked this answer from: https://stackoverflow.com/a/17785576/514483

    number.to_s(26).tr("0123456789abcdefghijklmnopq", "ABCDEFGHIJKLMNOPQRSTUVWXYZ")
    
    0 讨论(0)
提交回复
热议问题