Search code examples
algorithmcombinationspermutation

Algorithm that gives a certain permutation of letters from an input value


I'm looking for a function that takes a certain input value and transforms it into a certain sequence of letters using the full alphabet.

This is the exact input: output I need:

5: aa
6: ab
7: ac
...
51: bu
52: bv
53: bw
...

And so on. And it should be able to continue with bigger input values creating combinations like aza, azb, azc or mnki, mnkj, mnkk.

Is this even possible, or do I just have to create all the permutations and store them? This would be easy, but memory intensive and slow and I don't need all permutations, just the one related to the input I'm giving.


Solution

  • Use base 26, interpreting the digits as a-z. You'll need to shift this to get 5 = aa.

    def convert_to_base_26(number)
      return '' if number == 0
      number += 22
      base = 26
      digits = ('a'..'z').to_a
    
      result = ''
      while number > 0
        number -= 1
        digit = number % base
        result = digits[digit] + result
        number /= base
      end
    
      result
    end
    
    
    > convert_to_base_26(51)
    => "bu"
    > convert_to_base_26(238_225)
    => "mnki"