An algorithm to calculate any given index of a cartesian product. Suppose we have 3 sequences -
- A : {1, 2, 3}
- B : {2, 6, 7, 9}
- C : {1, 7}
Simply call get_tuple_by_index and pass in the list/array of sequences (i.e [A, B, C] or {A, B, C}) and the index of the result you want.
For C (the programming language), you'd also need to pass in the number of sequences (3 in this case) and an array containing the lengths of each sequences ({3, 4, 2} in this case).
For example, if we'd call get_tuple_by_index with the 6th index (starting from 0) of the cartesian product A x B x C, we'd get (1, 9, 1)
For this demonstration, we'll be using the sequences mentioned above as examples
- 
The list/arrayof sequences, that we'd like the cartesian product to, in this case[A, B, C]or{A, B, C}is reverse iterated through.
- 
In each iteration, the result tupleis filled up from backwards.
- 
In each iteration, the current elementof theresult tuplewill be theindex % length_of_current_setth index of the current set.
- 
Additionally, in each iteration, the indexis set toindex // length_of_current_setwhere//signifies integer division So, in this case, in the first iteration, forindex = 6, thecurrent elementwill beC[6 % 2]orC[0]or1. That will now be added as the last element ofresult tuple. It'll now look like ->(1)indexis now set to6 // 2or3In the second iteration, the current elementwill beB[3 % 4]orB[3]or9. That will now be added as the second to last element ofresult tuple. It'll now look like ->(9, 1)indexis now set to3 // 4or0In the third iteration, the current elementwill beA[0 % 3]orA[0]or1. That will now be added as the third to last element (or first element in this case) ofresult tuple. It'll now look like ->(1, 9, 1)