I assume that when you say this easily for a fixed length, you use m nested loops, where m is the length of the sequence (2 and 3 in your examples).
You can use recursion as follows:
Your words are numbered 0, 1, .. n, you need to generate all sequences of length m:
generate all sequences of length m: { start with 0, and generate all sequences of length m-1 start with 1, and generate all sequences of length m-1 ... start with n, and generate all sequences of length m-1 } generate all sequences of length 0 { // nothing to do }
How to implement this? Well, in each call you can push another element to the end of the array, and when you press the end of the recursion, print the contents of the array:
// m is remaining length of sequence, elements is array with numbers so far generate(m, elements) { if (m == 0) { for j = 0 to elements.length print(words[j]); } else { for i = 0 to n - 1 { generate(m-1, elements.push(i)); } } }
And finally, name it like this: generate (6, array ())
source share