# [thelist] Generating possible combinations without nested loops

Hassan Schroeder hassan.schroeder at gmail.com
Sat Aug 24 20:34:04 CDT 2013

```On Fri, Aug 23, 2013 at 7:29 PM, erik mattheis <gozz at gozz.com> wrote:

>
> for (a in 0...2) {
>  for (b in 0...2) {
>   for (c in 0...2) {
>     test(a,b,c);
>    }
>   }
> }
>
> but I'm wondering if there's a more efficient (or eloquent) way of
> generating the required permutations of a,b and c. Ideas?
>

In Ruby:

2.0.0-p247 :087 > a,b,c = [1,2,3], [4,5,6], [7,8,9]
=> [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
2.0.0-p247 :088 > a.product(b).product(c).map(&:flatten)
=> [[1, 4, 7], [1, 4, 8], [1, 4, 9], [1, 5, 7], [1, 5, 8], [1, 5, 9], [1,
6, 7], [1, 6, 8], [1, 6, 9], [2, 4, 7], [2, 4, 8], [2, 4, 9], [2, 5, 7],
[2, 5, 8], [2, 5, 9], [2, 6, 7], [2, 6, 8], [2, 6, 9], [3, 4, 7], [3, 4,
8], [3, 4, 9], [3, 5, 7], [3, 5, 8], [3, 5, 9], [3, 6, 7], [3, 6, 8], [3,
6, 9]]
2.0.0-p247 :089 >

Eloquence is in the eye of the beholder, but it's certainly succinct :-)

HTH!
--
Hassan Schroeder ------------------------ hassan.schroeder at gmail.com
http://about.me/hassanschroeder
twitter: @hassan
```

More information about the thelist mailing list