Iterative Cartesian Product in Java

前端 未结 9 1899
既然无缘
既然无缘 2020-11-27 07:00

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

I\'ve wrote that iterative code...

public s         


        
9条回答
  •  悲哀的现实
    2020-11-27 07:38

    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!

提交回复
热议问题