fork download
  1. let (<<) f g x = f (g x)
  2. let flip f x y = f y x
  3. let cumulate f init =
  4. let rec aux acc = function
  5. 0 -> acc
  6. | n -> aux (f acc n) (n - 1)
  7. in aux init
  8. let factorial = cumulate ( * ) 1
  9. let power x = cumulate (fun acc _ -> acc * x) 1
  10. let range = cumulate (fun acc n -> n - 1 :: acc) []
  11. let repeat x = cumulate (fun acc _ -> x :: acc) []
  12. let repelem m = List.concat << List.map (flip repeat m)
  13. let println to_s = Printf.printf "[%s]\n" << String.concat ", " << List.map to_s
  14. let delete_at i =
  15. let rec aux j rs = function
  16. [] -> (None, List.rev rs)
  17. | x :: xs when j = i -> (Some x, List.rev_append rs xs)
  18. | x :: xs -> aux (j + 1) (x :: rs) xs
  19. in aux 0 []
  20. let count f =
  21. List.fold_left (fun acc x -> acc + if f x then 1 else 0) 0
  22. let println_opt to_s = function
  23. None -> print_endline "None"
  24. | Some x -> println to_s x
  25. let f r m n =
  26. let a = repelem m @@ List.map ((+) 1) @@ range r in
  27. let x = factorial (r * m) / power (factorial m) r in
  28. let rec aux acc x n = function
  29. [] -> Some (List.rev acc)
  30. | a ->
  31. let y = float_of_int x /. float_of_int (List.length a) in
  32. let i = int_of_float (float_of_int ((n - 1) mod x) /. y) in
  33. match delete_at i a with
  34. None, _ -> None
  35. | Some d, rest ->
  36. let x = int_of_float ((float_of_int (1 + count ((=) d) rest)) *. y) in
  37. let n = n - int_of_float ((float_of_int (count ((>) d) rest)) *. y) in
  38. aux (d :: acc) x n rest
  39. in if n < 1 || x < n then None else aux [] x n a
  40. let g r m n = println_opt string_of_int @@ f r m n
  41. let () =
  42. g 9 1 1;
  43. g 9 1 2;
  44. g 9 1 3;
  45. g 9 1 123456;
  46. g 9 1 234567;
  47. g 9 1 362880;
  48. g 4 3 1;
  49. g 4 3 2;
  50. g 4 3 3;
  51. g 4 3 123456;
  52. g 4 3 234567;
  53. g 4 3 369600;
  54.  
Success #stdin #stdout 0s 5328KB
stdin
Standard input is empty
stdout
[1, 2, 3, 4, 5, 6, 7, 8, 9]
[1, 2, 3, 4, 5, 6, 7, 9, 8]
[1, 2, 3, 4, 5, 6, 8, 7, 9]
[4, 1, 6, 5, 8, 9, 7, 3, 2]
[6, 8, 4, 7, 5, 3, 2, 1, 9]
[9, 8, 7, 6, 5, 4, 3, 2, 1]
[1, 1, 1, 2, 2, 2, 3, 3, 3, 4, 4, 4]
[1, 1, 1, 2, 2, 2, 3, 3, 4, 3, 4, 4]
[1, 1, 1, 2, 2, 2, 3, 3, 4, 4, 3, 4]
[2, 2, 2, 3, 3, 1, 4, 3, 4, 1, 1, 4]
[3, 2, 4, 4, 2, 4, 3, 3, 1, 1, 1, 2]
[4, 4, 4, 3, 3, 3, 2, 2, 2, 1, 1, 1]