質問

F#での要素の組み合わせの最もエレガントでシンプルな実装に関するもう1つの質問。

入力要素のすべての組み合わせ(リストまたはシーケンス)を返す必要があります。 最初の引数は、組み合わせの要素の数です。

例:

comb 2 [1;2;2;3];;
[[1;2]; [1;2]; [1;3]; [2;2]; [2;3]; [2;3]]
役に立ちましたか?

解決

sspよりも簡潔かつ高速なソリューション:

let rec comb n l = 
    match n, l with
    | 0, _ -> [[]]
    | _, [] -> []
    | k, (x::xs) -> List.map ((@) [x]) (comb (k-1) xs) @ comb k xs

他のヒント

let rec comb n l =
  match (n,l) with
  | (0,_) -> [[]]
  | (_,[]) -> []
  | (n,x::xs) ->
      let useX = List.map (fun l -> x::l) (comb (n-1) xs)
      let noX = comb n xs
      useX @ noX

より簡潔なバージョンのKVの回答があります:

let rec comb n l =
  match (n,l) with
    | (0,_) -> [[]]
    | (_,[]) -> []
    | (n,x::xs) ->
      List.flatten [(List.map (fun l -> x::l) (comb (n-1) xs)); (comb n xs)]

ツリーの再帰に精通している場合、受け入れられる答えは豪華ですぐに理解できます。優雅さが求められていたため、この長い休止スレッドを開くことはいくぶん不必要に思えます。

ただし、よりシンプルなソリューションが求められました。反復アルゴリズムは、私には時々簡単に思えます。さらに、パフォーマンスは品質の指標として言及されており、反復プロセスは再帰プロセスよりも速い場合があります。

次のコードは末尾再帰であり、反復プロセスを生成します。 24個の要素のリストからサイズ12の組み合わせを計算するには、時間の3分の1が必要です。

let combinations size aList = 
    let rec pairHeadAndTail acc bList = 
        match bList with
        | [] -> acc
        | x::xs -> pairHeadAndTail (List.Cons ((x,xs),acc)) xs
    let remainderAfter = aList |> pairHeadAndTail [] |> Map.ofList
    let rec comboIter n acc = 
        match n with
        | 0 -> acc
        | _ -> 
            acc
            |> List.fold (fun acc alreadyChosenElems ->
                match alreadyChosenElems with
                | [] -> aList //Nothing chosen yet, therefore everything remains.
                | lastChoice::_ -> remainderAfter.[lastChoice]
                |> List.fold (fun acc elem ->
                    List.Cons (List.Cons (elem,alreadyChosenElems),acc)
                ) acc
            ) []
            |> comboIter (n-1)
    comboIter size [[]]

反復プロセスを許可する考え方は、最後に選択した要素のマップを残りの利用可能な要素のリストに事前計算することです。このマップは remainderAfter に保存されます。

コードは簡潔ではなく、叙情的な拍子や韻に準拠していません。

シーケンス式を使用した naive 実装。個人的には、シーケンス式は他のより密度の高い関数よりも簡単だと感じることがよくあります。

let combinations (k : int) (xs : 'a list) : ('a list) seq =
    let rec loop (k : int) (xs : 'a list) : ('a list) seq = seq {
        match xs with
        | [] -> ()
        | xs when k = 1 -> for x in xs do yield [x]
        | x::xs ->
            let k' = k - 1
            for ys in loop k' xs do
                yield x :: ys
            yield! loop k xs }
    loop k xs
    |> Seq.filter (List.length >> (=)k)

離散数学とその応用から取られた方法。 結果は、配列に格納された組み合わせの順序付きリストを返します。 インデックスは1から始まります。

let permutationA (currentSeq: int []) (n:int) (r:int): Unit = 
    let mutable i = r
    while currentSeq.[i - 1] = n - r + i do
        i <- (i - 1)
    currentSeq.[i - 1] <- currentSeq.[i - 1] + 1
    for j = i + 1 to r do
        currentSeq.[j - 1] <- currentSeq.[i - 1] + j - i   
    ()
let permutationNum (n:int) (r:int): int [] list =
    if n >= r then
        let endSeq = [|(n-r+1) .. n|]
        let currentSeq: int [] = [|1 .. r|]
        let mutable resultSet: int [] list = [Array.copy currentSeq];
        while currentSeq <> endSeq do
            permutationA currentSeq n r
            resultSet <- (Array.copy currentSeq) :: resultSet
        resultSet
    else
        []

このソリューションは単純であり、ヘルパー関数は一定のメモリを消費します。

私の解決策は、簡潔さや効率性は劣ります(また、直接再帰は使用されません)が、すべての組み合わせ(現在はペアのみ、2つのリストのタプルを返すためにfilterOutを拡張する必要がありますが、後ほどほとんど行いません)を返します。

let comb lst =
    let combHelper el lst =
        lst |> List.map (fun lstEl -> el::[lstEl])
    let filterOut el lst =
        lst |> List.filter (fun lstEl -> lstEl <> el)
    lst |> List.map (fun lstEl -> combHelper lstEl (filterOut lstEl lst)) |> List.concat

comb [1; 2; 3; 4]は以下を返します。     [[1; 2]; [1; 3]; [1; 4]; [2; 1]; [2; 3]; [2; 4]; [3; 1]; [3; 2]; [3; 4]; [4; 1]; [4; 2]; [4; 3]]

わかりました、テールの組み合わせは少し異なるアプローチです(ライブラリ関数を使用しない)

let rec comb n lst =
    let rec findChoices = function
      | h::t -> (h,t) :: [ for (x,l) in findChoices t -> (x,l) ]
      | []   -> []
    [ if n=0 then yield [] else
            for (e,r) in findChoices lst do
                for o in comb (n-1) r do yield e::o  ]
ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top