8 people like it.

Combinations n choose k

given an array n generates all lists with k choices from n

 1: 
 2: 
 3: 
 4: 
 5: 
 6: 
 7: 
 8: 
 9: 
10: 
let n_choose_k n k = let rec choose lo  =
                         function
                         |0 -> [[]]
                         |i -> [for j in lo .. (Array.length n)-1 do
                                     for ks in choose (j+1) (i-1) do
                                       yield n.[j] :: ks ]
                     in choose 0  k                           
                         

n_choose_k [|'a' .. 'f'|] 3 ;;
val n_choose_k : n:'a [] -> k:int -> 'a list list

Full name: Script.n_choose_k
val n : 'a []
val k : int
val choose : (int -> int -> 'a list list)
val lo : int
val i : int
val j : int
module Array

from Microsoft.FSharp.Collections
val length : array:'T [] -> int

Full name: Microsoft.FSharp.Collections.Array.length
val ks : 'a list

More information

Link:http://fssnip.net/fF
Posted:12 years ago
Author:isaiah perumalla
Tags: algorithms , combinations