As you may have understood with the title, I need some smart thinking here :)
I have a List<List<Object>>
object. If you think of the Object objects as integers, you could see it like this :
{{1,2},{10,20,30},{100}}
I need to get all possible lists containing exactly one element of each list, that is, come up with this :
{{1,10,100},{1,20,100},{1,30,100},{2,10,100},{2,20,100},{2,30,100}}
Of course you don't know at compiling time how much items the lists will contain, so you cannot rely on an overlapping of for
loops...
How would you come up with this? Time constraints are not relevant to my problem because the lists will likely contain few elements.
Just for completeness, what you are searching is called the Cartesian product of your lists, called such since the size of our result list is the product of the sizes of the individual lists.
Edit: Here is an implementation which works for arbitrary Iterables of Iterables, and creates an Iterable of lists. It creates the elements lazily on iteration, so it works for really big products which don't fit in the memory all at one, too.
One more edit: here is a index-based lazy list implementation.
I added implementations of contains, indexOf and lastIndexOf which are quite better than the original ones from AbstractList (or AbstractCollection) (for bigger factors than in your example, at least). These are not optimized for the sublists, since the sublists are simply taken from AbstractList.
You might use that scala code:
Since crossproduct is another name for cartesian product, it's name is xproduct.
Iterative algorithm.
*Notice that this code not for production! You should replace
LinkedList
withArrayList
with initial size, make checks and so on.upd usage example provided. there is some code improvement. But it still only draft. I wouldn't recommend you use it in real tasks.
I won't implement it, but here's an idea for a recursive algorithm:
{{1,2,3}}
), then the result is - of course - a list of lists containing one element each (i.e.e.g.{{1},{2},{3}}
Here's raw Python code:
Here is a java implementation of phimuemue's Python algorithm.
Feel free to comment further. Thank you for all your efforts !
Simple iterative algorithm.
If necessary, an explanation, just let me know.