I'm trying to self-learn some programming in a functional programming language and recently stumbled on the problem of generating all the permutations of length m
from a list of length n
, with repetition. Mathematically, this should result in a total of n^m
possible permutations, because each of the m
'slots' can be filled with any of the n
elements. The code I have currently, however, does not give me all the elements:
let rec permuts n list =
match n, list with
0, _ -> [[]]
| _, [] -> []
| n, h :: t -> (List.map (fun tt -> h::tt) (permuts (n-1) list))
@ permuts n t;;
The algorithm basically takes one element out of a list with m
elements, slaps it onto the front of all the combinations with the rest of the elements, and concatenates the results into one list, giving only n C m
results.
For example, the output for permuts 2 [1;2;3]
yields
[[1;1]; [1;2]; [1;3]; [2;2]; [2;3]; [3;3]]
whereas I actually want
[[1;1]; [1;2]; [1;3]; [2;1]; [2;2]; [2;3]; [3;1]; [3;2]; [3;3]]
-- a total of 9 elements. How do I fix my code so that I get the result I need? Any guidance is appreciated.