Get combinations of digits in a sequence
- Posted by jmduro Aug 17, 2017
- 1570 views
Here are 2 recursive functions that give all combinations of digits in a sequence.
sequence combinations procedure get_all_combinations(sequence s, sequence used, integer n) integer lg lg = length(s) if n = lg then combinations = append(combinations, used) return end if n += 1 for d = 1 to length(s[n]) do get_all_combinations(s, used&s[n][d], n) end for end procedure ------------------------------------------------------------------------------ procedure get_unique_combinations(sequence s, sequence used, integer n) integer lg lg = length(s) if n = lg then combinations = append(combinations, used) return end if n += 1 for d = 1 to length(s[n]) do if not find(s[n][d], used) then get_unique_combinations(s, used&s[n][d], n) end if end for end procedure
And here is an example of usage:
constant SEQ = {{4,8,9}, {1,2,4}, {1,4,5,6}} combinations = {} get_all_combinations(SEQ, {}, 0) pretty_print(1, combinations, {}) puts(1, "\n") combinations = {} get_unique_combinations(SEQ, {}, 0) pretty_print(1, combinations, {}) puts(1, "\n")
Here is the result: get_all_combinations allows duplicate digits, get_unique_combinations does not.
{ {4,1,1}, {4,1,4}, {4,1,5}, {4,1,6}, {4,2,1}, {4,2,4}, {4,2,5}, {4,2,6}, {4,4,1}, {4,4,4}, {4,4,5}, {4,4,6}, {8,1,1}, {8,1,4}, {8,1,5}, {8,1,6}, {8,2,1}, {8,2,4}, {8,2,5}, {8,2,6}, {8,4,1}, {8,4,4}, {8,4,5}, {8,4,6}, {9,1,1}, {9,1,4}, {9,1,5}, {9,1,6}, {9,2,1}, {9,2,4}, {9,2,5}, {9,2,6}, {9,4,1}, {9,4,4}, {9,4,5}, {9,4,6} } { {4,1,5}, {4,1,6}, {4,2,1}, {4,2,5}, {4,2,6}, {8,1,4}, {8,1,5}, {8,1,6}, {8,2,1}, {8,2,4}, {8,2,5}, {8,2,6}, {8,4,1}, {8,4,5}, {8,4,6}, {9,1,4}, {9,1,5}, {9,1,6}, {9,2,1}, {9,2,4}, {9,2,5}, {9,2,6}, {9,4,1}, {9,4,5}, {9,4,6} }
Jean-Marc