cancel
Showing results for 
Show  only  | Search instead for 
Did you mean: 
Choose Language Hide Translation Bar
miguello
Level VI

Iterate through all combinations of values from ARBITRARY number of lists

Can somebody suggest a solution to this.

I have multiple lists. I need to iterate through all possible combinations of values from these lists. The problem is that the number of lists I'm taking values from is decided at runtime. So I cannot write two nested 'for' loops for two lists and then three nested 'for' loops for three lists. I need somehow to pass\parse names of the lists (probably as a list itself) and then iterate through all of the lists\values in the lists.

Any ideas?

 

1 REPLY 1
Craige_Hales
Super User

Re: Iterate through all combinations of values from ARBITRARY number of lists

I'm not sure how deep this can go before JMP thinks your recursion is too deep, so test first...If you have too many lists, there is a slightly less pretty work-around using a stack. But if each list has at least two elements, I think you'll run out of time first.

// the variable length list of variable length lists
L = {{"a", "b"}, {"c"}, {"d", "e", "f"}, {"g", "h", "i", "j"}};

result = {}; // a place to accumulate the results
p = {}; // a single result

// a recursive function to "nest the for loops"
generate = Function( {i}, // the "layer"
	{j}, // the local for-loop counter
	If( i > N Items( L ),
		result[N Items( result ) + 1] = p; // you could just use p at this point
		Return();
	);
	For( j = 1, j <= N Items( L[i] ), j += 1, // go through all the items at this layer
		Insert Into( p, L[i][j] ); // add each to the single result
		Recurse( i + 1 ); // go to next layer
		Remove From( p ); // remove from the single result
	);
);

generate( 1 ); // run the recursive function
Show( result );

result = {

{"a", "c", "d", "g"},

{"a", "c", "d", "h"},

{"a", "c", "d", "i"},

{"a", "c", "d", "j"},

{"a", "c", "e", "g"},

{"a", "c", "e", "h"},

{"a", "c", "e", "i"},

{"a", "c", "e", "j"},

{"a", "c", "f", "g"},

{"a", "c", "f", "h"},

{"a", "c", "f", "i"},

{"a", "c", "f", "j"},

{"b", "c", "d", "g"},

{"b", "c", "d", "h"},

{"b", "c", "d", "i"},

{"b", "c", "d", "j"},

{"b", "c", "e", "g"},

{"b", "c", "e", "h"},

{"b", "c", "e", "i"},

{"b", "c", "e", "j"},

{"b", "c", "f", "g"},

{"b", "c", "f", "h"},

{"b", "c", "f", "i"},

{"b", "c", "f", "j"}

};

 

Craige