Calculating the nth Term of a Cartesian Product

I recently had to calculate the nth term for a Cartesian Product. I wanted to avoid generating the entire Cartesian Product in order to jump to the nth term. I wanted a way to derive the nth term.

For example, let's say I have two arrays:

a = [
  [1,2,3],
  [4,5]
]


The Cartesian Product of the above two arrays can be:

[[1, 4], [1, 5], [2, 4], [2, 5], [3, 4], [3, 5]]


Now, when I ask for the 3rd term of the above cartesian product, I want to receive [3,4]. Again, I want to do this without calculating the entire set.

My solution is below:

def combo(arrays, num)
  arrays.map do |a|
    v = a[num % a.length]
    num /= a.length
    v
  end
end


Example:

term = combo(a, 2)
puts term.inspect
# [2,4]


The next trick is to turn [2,4] back into 2.

Suggestions for how to improve this?

Popular posts from this blog

Lists and arrays in Dart

The 29 Healthiest Foods on the Planet

Converting Array to List in Scala