Skip to content
Advertisement

Iteratively compute the Cartesian product of an arbitrary number of sets

I want to compute the cartesian product of an arbitrary number of nonempty sets in Java.

I’ve wrote that iterative code…

JavaScript

…but I found it rather inelegant. Someone has a better, still iterative solution? A solution that uses some wonderful functional-like approach? Otherwise… suggestion about how to improve it? Errors?

Advertisement

Answer

I’ve written a solution that doesn’t require you to fill up a large collection in memory. Unfortunately, the code required is hundreds of lines long. You may have to wait until it appears in the Guava project (https://github.com/google/guava), which I hope will be by the end of the year. Sorry. 🙁

Note that you may not need such a utility if the number of sets you’re cartesian-producting is a fixed number known at compile time — you could just use that number of nested for loops.

EDIT: the code is released now.

Sets.cartesianProduct()

I think you’ll be very happy with it. It only creates the individual lists as you ask for them; doesn’t fill up memory with all MxNxPxQ of them.

If you want to inspect the source, it’s here.

Enjoy!

User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement