Iterate set covered by cross-product of ranges in ruby

Posted by wilsona on Stack Overflow See other posts from Stack Overflow or by wilsona
Published on 2011-02-19T14:26:47Z Indexed on 2011/02/19 15:25 UTC
Read the original article Hit count: 225

Filed under:
|
|
|

I figured this answer had been asked before, so I searched, but I couldn't find anything. Granted, there are a ton of Ruby Array questions, so it might be there, just buried.

In any case, I'm trying to reduce a cross-product of ranges, returning a sum of all elements of the cross-product that meet some set of conditions. To construct a trivial example, if I have an array like this:

[0..1,0..1,0..1]

I'd like to iterate over this set:

[
  [0,0,0],
  [0,0,1],
  [0,1,0],
  [0,1,1],
  [1,0,0],
  [1,0,1],
  [1,1,0],
  [1,1,1]
]

and return a sum based the condition "return 1 if i[0] == 1 and i[2] == 0" (which would give 2). In my contrived example, I could do it like this:

br = 0..1

br.reduce(0){|sumx, x|
  sumx + br.reduce(0){|sumy, y|
    sumy + br.reduce(0){|sumz, z|
      sumz + (x == 1 and z == 0 ? 1 : 0)
    }
  }
}

, but in the actual application, the set of ranges might be much larger, and nesting reduces that way would get quite ugly. Is there a better way?

© Stack Overflow or respective owner

Related posts about ruby

Related posts about arrays