Creating an array containing sums of combinations of ranges

I’ve got a puzzle I haven’t been able to solve. I have two user-provided
arrays that look something like this:

[1…2, 2…3]

and

[2, 3]

I need to produce an array containing every possible sum of the ranges
multiplied by the corresponding member of the second array. i.e. if the
first array is [n, m] and the second array is [x, y], I need an array
containing every possible (nx + my).

Normally I’d do a couple of nested loops, but I need the arrays can be
of arbitrary lengths.

How should I go about this?

Jeff,

Saturday, April 14, 2012, 5:54:41 PM, you wrote:

JC> I’ve got a puzzle I haven’t been able to solve. I have two
user-provided
JC> arrays that look something like this:

JC> [1…2, 2…3]

JC> and

JC> [2, 3]

JC> I need to produce an array containing every possible sum of the
ranges
JC> multiplied by the corresponding member of the second array. i.e. if
the
JC> first array is [n, m] and the second array is [x, y], I need an
array
JC> containing every possible (nx + my).

JC> Normally I’d do a couple of nested loops, but I need the arrays can
be
JC> of arbitrary lengths.

JC> How should I go about this?

Could you give some more examples. Your English is a bit ambiguous.

Have you thought about using something like Cucumber to specify the
problem?

Ralph S.

Jake,
That’s exactly what I was looking for. Thank you!

hi Jeff,

have you checked out Array#product ? seems like that might do the
trick for you…

a1 = [‘n’, ‘m’]
a2 = [‘x’, ‘y’]

p a1.product(a2)

=> [[“n”, “x”], [“n”, “y”], [“m”, “x”], [“m”, “y”]]

if your first array is composed of ranges, those can easily be
converted into arrays with Range#to_a…

hth-

  • j