Created
September 15, 2012 12:55
-
-
Save miklund/3727669 to your computer and use it in GitHub Desktop.
Function to permute a list into permutations with fixed length
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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