How can I generate all possible combinations consisting of elements of given n sets? For example, if there are 3 sets:

A=1,2,3,4,... B=a,b,c,d,... C=A,B,C,D,... 

and you need to get something like:

 1 a A; 1 b A; 1 c A .... 1 a B; 1 b B 

In this case, the number n is not known in advance, so it’s impossible to solve nested loops.

  • You can also google the implementation of the "cartesian product" for your programming language - alvoro

1 answer 1

Imagine that these are numbers on the appropriate places of a number.

Create the first number - 1aA (or how many places you need there). Then simply increase the last element until we sort through everything. After that, we set it equal to the minimum element and increase the previous one (if it is also maximal, drop it to the minimum and proceed to the previous one).

 1aA 1aB 1aC // достигли максимума Π² послСднСй ΠΏΠΎΠ·ΠΈΡ†ΠΈΠΈ. ΠΏΠ΅Ρ€Π΅Ρ…ΠΎΠ΄- 1bA 1bB 1bC // достигли максимума Π² послСднСй ΠΏΠΎΠ·ΠΈΡ†ΠΈΠΈ. ΠΏΠ΅Ρ€Π΅Ρ…ΠΎΠ΄- 1bA 1bB 1bC // достигли максимума Π² послСднСй ΠΏΠΎΠ·ΠΈΡ†ΠΈΠΈ. ΠΏΠ΅Ρ€Π΅Ρ…ΠΎΠ΄- 1bA 1bB 1bC // достигли максимума Π² послСднСй ΠΏΠΎΠ·ΠΈΡ†ΠΈΠΈ. ΠΏΠ΅Ρ€Π΅Ρ…ΠΎΠ΄- 1сA 1сB 1сC // достигли максимума Π² послСднСй ΠΏΠΎΠ·ΠΈΡ†ΠΈΠΈ. ΠΏΠ΅Ρ€Π΅Ρ…ΠΎΠ΄- Π½ΠΎ Π²ΠΎ Π²Ρ‚ΠΎΡ€ΠΎΠΉ ΠΏΠΎΠ·ΠΈΡ†ΠΈΠΈ // Ρ‚ΠΎΠΆΠ΅ максимум, пСрСнос Π΄Π°Π»Π΅Π΅ 2aA ... 

In a word, we simply implement the algorithm M ( Generation in a mixed positional number system ) from page 330 4A of the volume β€œProgramming Arts” ...