Java/ Efficient way to find all permutation of lists -
this question has answer here:
i have list of lists in java: {{1,2},{3,4,5},{6,7,8}}
i try find permutations of list. meaning, in result list next: {{1,3,6},{1,3,7},{1,3,8},{1,4,6}....{2,5,8}}
there reasonable way it?
here list<list<integer>
implementation.
static public void main(string[] argv) { list<list<integer>> lst = new arraylist<list<integer>>(); lst.add(arrays.aslist(1, 2)); lst.add(arrays.aslist(3, 4, 5)); lst.add(arrays.aslist(6, 7, 8)); list<list<integer>> result = null; result = cartesian(lst); (list<integer> r : result) { (integer : r) { system.out.print(i + " "); } system.out.println(); } } static public list<list<integer>> cartesian(list<list<integer>> list) { list<list<integer>> result = new arraylist<list<integer>>(); int numsets = list.size(); integer[] tmpresult = new integer[numsets]; cartesian(list, 0, tmpresult, result); return result; } static public void cartesian(list<list<integer>> list, int n, integer[] tmpresult, list<list<integer>> result) { if (n == list.size()) { result.add(new arraylist<integer>(arrays.aslist(tmpresult))); return; } (integer : list.get(n)) { tmpresult[n] = i; cartesian(list, n + 1, tmpresult, result); } }
Comments
Post a Comment