关于组合:具有重复ocaml的列表中的排列

permutation in a list with repetition ocaml

我有一个函数,可以使从列表的N个元素中选择的K个不同的对象组合在一起,问题是不会重复出现,例如:

提取2 [" a "; " b "; " c "; " d "] ;;
-:字符串列表列表=
[["一种"; " b "]; ["一种"; "C"]; ["一种"; " d "]; [" b "; "C"]; [" b "; " d "]; ["C"; " d "]]

这是我的代码:

1
2
3
4
5
6
7
8
# let rec extract k list =
if k <= 0 then [ [] ]
else match list with
     | [] -> []
     | h :: tl ->
        let with_h = List.map (fun l -> h :: l) (extract (k-1) tl) in
        let without_h = extract k tl in
        with_h @ without_h;;

感谢您的回复,我正在尝试找出解决方法。


I have a function that makes combinations of K distinct objects

的确。

the problem is doesn't permute with repetition,

这并不比组合难得多。有两种方法可以进行归纳步骤。如果要置换(非空)集Ak个元素,则可以:

方法1

对于A中的每个元素x,计算A\\{x}k-1个元素的排列,并将x放在所有这些排列的前面。然后加入为每个x

获得的解决方案集。

方法2

A中选择一个x,计算A\\{x}k-1个元素的排列,然后对于找到的每个排列,通过在每个可能的位置插入x来计算新的排列。