Download code

Jump to: navigation, search

Back to Kth_permutation_(OCaml)

Download for Windows: single file, zip

Download for UNIX: single file, zip, tar.gz, tar.bz2

kthperm.ml

 1 (* The authors of this work have released all rights to it and placed it
 2 in the public domain under the Creative Commons CC0 1.0 waiver
 3 (http://creativecommons.org/publicdomain/zero/1.0/).
 4 
 5 THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
 6 EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
 7 MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
 8 IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
 9 CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
10 TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
11 SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
12 
13 Retrieved from: http://en.literateprograms.org/Kth_permutation_(OCaml)?oldid=17522
14 *)
15 
16 let rec rr n k =
17   if n = 0 then
18     []
19   else
20     k mod n :: rr (n-1) (k / n)
21 
22 let dfr xs = List.fold_right
23               (fun x rs -> x :: List.map (fun r -> r + (if x <= r then 1 else 0)) rs)
24               xs []
25 let par rs = List.fold_left (+) 0 rs mod 2
26 let perm xs k = List.map (List.nth xs) (dfr (rr (List.length xs) k))
27 let list_of_string str =
28   let result = ref [] in
29   String.iter (fun x -> result := x :: !result)
30               str;
31   List.rev !result
32  
33 let string_of_list lst =
34   let result = String.create (List.length lst) in
35   ignore (List.fold_left (fun i x -> result.[i] <- x; i+1) 0 lst);
36   result
37 ;;
38 
39 for k = 0 to 23 do
40   Printf.printf "%s %d\n" (string_of_list (perm (list_of_string "perm") k))
41                           (par (rr 4 k))
42 done;;


hijacker
hijacker
hijacker
hijacker