Skip to content

Instantly share code, notes, and snippets.

@miklund
Created September 15, 2012 12:55
Show Gist options
  • Save miklund/3727669 to your computer and use it in GitHub Desktop.
Save miklund/3727669 to your computer and use it in GitHub Desktop.
Function to permute a list into permutations with fixed length
// wide depth lft rgt
// depth: the length of result lists
// lft: the left list (default [])
// rgt: the right list (default items we want to permute)
//
// example: wide 2 [] [1; 2; 3]
// -> [[1; 2]; [1; 3]; [2; 1]; [2; 3]; [3; 2]; [3; 1]]
let rec wide depth lft = function
| [] -> []
| hd :: tl -> (deep hd (depth, (lft @ tl))) @ (wide depth (hd :: lft) tl)
and deep x = function
| 1, _ | _, [] -> [[x]]
| d, l -> List.map (fun i -> x :: i) (wide (d - 1) [] l)
// permute length items, utility method to wide/deep
//
// example: permute 2 [1..3]
// -> [[1; 2]; [1; 3]; [2; 1]; [2; 3]; [3; 2]; [3; 1]]
let permute length = wide length []
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment