0 people like it.

combinations with k items from n items

get all combinations (as array index values) with k items from n items. indexes are 1 based

 1: 
 2: 
 3: 
 4: 
 5: 
 6: 
 7: 
 8: 
 9: 
10: 
11: 
12: 
let getallcombinations n k =
    let rec f k start =
        [
            for i in start .. n do
                match k with
                | 1 -> yield [i]
                | _ -> yield! f (k-1) (i+1) |> List.map (fun ls -> i :: ls)
        ]
    f k 1

// getallcombinations 4 2
// [[1; 2]; [1; 3]; [1; 4]; [2; 3]; [2; 4]; [3; 4]]
val getallcombinations : n:int -> k:int -> int list list
val n : int
val k : int
val f : (int -> int -> int list list)
val start : int
val i : int
Multiple items
module List

from Microsoft.FSharp.Collections

--------------------
type List<'T> =
  | ( [] )
  | ( :: ) of Head: 'T * Tail: 'T list
    interface IReadOnlyList<'T>
    interface IReadOnlyCollection<'T>
    interface IEnumerable
    interface IEnumerable<'T>
    member GetReverseIndex : rank:int * offset:int -> int
    member GetSlice : startIndex:int option * endIndex:int option -> 'T list
    member Head : 'T
    member IsEmpty : bool
    member Item : index:int -> 'T with get
    member Length : int
    ...
val map : mapping:('T -> 'U) -> list:'T list -> 'U list
val ls : int list

More information

Link:http://fssnip.net/858
Posted:2 years ago
Author:snuup
Tags: combinations