tasks a-s
This commit is contained in:
parent
47bf37c096
commit
b83f433714
12433 changed files with 156208 additions and 123 deletions
45
Task/Permutations/OCaml/permutations-1.ocaml
Normal file
45
Task/Permutations/OCaml/permutations-1.ocaml
Normal file
|
|
@ -0,0 +1,45 @@
|
|||
(* Iterative, though loops are implemented as auxiliary recursive functions.
|
||||
Translation of Ada version. *)
|
||||
let next_perm p =
|
||||
let n = Array.length p in
|
||||
let i = let rec aux i =
|
||||
if (i < 0) || (p.(i) < p.(i+1)) then i
|
||||
else aux (i - 1) in aux (n - 2) in
|
||||
let rec aux j k = if j < k then
|
||||
let t = p.(j) in
|
||||
p.(j) <- p.(k);
|
||||
p.(k) <- t;
|
||||
aux (j + 1) (k - 1)
|
||||
else () in aux (i + 1) (n - 1);
|
||||
if i < 0 then false else
|
||||
let j = let rec aux j =
|
||||
if p.(j) > p.(i) then j
|
||||
else aux (j + 1) in aux (i + 1) in
|
||||
let t = p.(i) in
|
||||
p.(i) <- p.(j);
|
||||
p.(j) <- t;
|
||||
true;;
|
||||
|
||||
let print_perm p =
|
||||
let n = Array.length p in
|
||||
for i = 0 to n - 2 do
|
||||
print_int p.(i);
|
||||
print_string " "
|
||||
done;
|
||||
print_int p.(n - 1);
|
||||
print_newline ();;
|
||||
|
||||
let print_all_perm n =
|
||||
let p = Array.init n (function i -> i + 1) in
|
||||
print_perm p;
|
||||
while next_perm p do
|
||||
print_perm p
|
||||
done;;
|
||||
|
||||
print_all_perm 3;;
|
||||
(* 1 2 3
|
||||
1 3 2
|
||||
2 1 3
|
||||
2 3 1
|
||||
3 1 2
|
||||
3 2 1 *)
|
||||
15
Task/Permutations/OCaml/permutations-2.ocaml
Normal file
15
Task/Permutations/OCaml/permutations-2.ocaml
Normal file
|
|
@ -0,0 +1,15 @@
|
|||
let rec permutations l =
|
||||
let n = List.length l in
|
||||
if n = 1 then [l] else
|
||||
let rec sub e = function
|
||||
| [] -> failwith "sub"
|
||||
| h :: t -> if h = e then t else h :: sub e t in
|
||||
let rec aux k =
|
||||
let e = List.nth l k in
|
||||
let subperms = permutations (sub e l) in
|
||||
let t = List.map (fun a -> e::a) subperms in
|
||||
if k < n-1 then List.rev_append t (aux (k+1)) else t in
|
||||
aux 0;;
|
||||
|
||||
let print l = List.iter (Printf.printf " %d") l; print_newline() in
|
||||
List.iter print (permutations [1;2;3;4])
|
||||
17
Task/Permutations/OCaml/permutations-3.ocaml
Normal file
17
Task/Permutations/OCaml/permutations-3.ocaml
Normal file
|
|
@ -0,0 +1,17 @@
|
|||
let rec pr_perm k n l =
|
||||
let a, b = let c = k/n in c, k-(n*c) in
|
||||
let e = List.nth l b in
|
||||
let rec sub e = function
|
||||
| [] -> failwith "sub"
|
||||
| h :: t -> if h = e then t else h :: sub e t in
|
||||
(Printf.printf " %d" e; if n > 1 then pr_perm a (n-1) (sub e l))
|
||||
|
||||
let show_perms l =
|
||||
let n = List.length l in
|
||||
let rec fact n = if n < 3 then n else n * fact (n-1) in
|
||||
for i = 0 to (fact n)-1 do
|
||||
pr_perm i n l;
|
||||
print_newline()
|
||||
done
|
||||
|
||||
let () = show_perms [1;2;3;4]
|
||||
Loading…
Add table
Add a link
Reference in a new issue