Search code examples
rubyrangeenumerate

Ruby get nth item from massive range


Suppose I have this range:

("aaaaa".."zzzzz")

How would I get the Nth item from the range without generating the entire thing before hand/each time?


Solution

  • Enumerate only up to n,

    or

    Develop a function that given a number n, f(n) gives you the nth item of your range of possible solutions.

    In your case you may treat your range as a number system with base 26. Rebasing a number is a well known problem. There's an example on my site to go from a base-10 number to a base-26 number (represented by the alphabet) even in ruby (made by a colleague of mine). Some variation of this algorithm would probably also work for you.

    Update Maybe it didn't sink in that this is your answer :D

    Here's the ruby code to get the nth item of your range:

    def rbase(value)
      a = ('a'..'z')
      b = a.to_a
      base = b.length
      text = []
      begin 
        value, rest = value.divmod(base)
        text << b[rest]
      end until value.zero?
      text.reverse.join
    end
    

    then you can use it like that.

    irb(main):030:0> rbase(789).rjust(10,'a')
    => "aaaaaaabej"