Tuesday, October 2, 2012

F# on Algorithms - Get Combinations

The code below generates the combination of elements in a list. The number of elements in the combination is  provided by user in the "elementNeeded" variable.

let getCombination (list:int list) elementNeeded =
    let rec getCombinationFunction (list:int list) elementNeeded currentList =
        if elementNeeded = 0 then
            [ currentList ]
        else
            [ for n in list do
                let newList =
                    list
                    |> Seq.skipWhile (fun x -> x<>n)
                    |> Seq.skip 1
                    |> Seq.toList
                let newElementNeeded = elementNeeded - 1
                for l in getCombinationFunction newList newElementNeeded (currentList@[n]) do
                    yield l ]

    getCombinationFunction list elementNeeded []

getCombination [1;2;3;4] 3

No comments: