fork download
  1. let rec take_while f xs =
  2. match xs with
  3. | [] -> []
  4. | x :: rest -> if f x
  5. then x :: take_while f rest
  6. else []
  7.  
  8. let rec drop_while f xs =
  9. match xs with
  10. | [] -> []
  11. | x :: rest -> if f x
  12. then drop_while f rest
  13. else xs
  14.  
  15. let span f xs = (take_while f xs, drop_while f xs)
  16.  
  17. let string_to_char_list s =
  18. let rec string_to_char_list_impl i l =
  19. if i < 0
  20. then l
  21. else string_to_char_list_impl (i - 1) (s.[i] :: l) in
  22. string_to_char_list_impl (String.length s - 1) []
  23.  
  24. let char_list_to_string cs =
  25. String.concat "" (List.map (fun x -> String.make 1 x) cs)
  26.  
  27. let next_permutation word =
  28. let rec next_permutation_impl char_list =
  29. match char_list with
  30. | x0 :: rest0 ->
  31. (match next_permutation_impl rest0 with
  32. | (true, rest1) -> (true, x0 :: rest1)
  33. | (false, rest1) ->
  34. (match rest1 with
  35. | [] -> (false, x0 :: rest1)
  36. | x1 :: _ ->
  37. if x0 < x1
  38. then
  39. let (left, right) = span (fun x -> x > x0) rest1 in
  40. let chunk =
  41. (match (List.rev left) with
  42. | [] -> List.concat [[x0]; right]
  43. | l :: revLeft -> List.concat [[l]; List.rev revLeft; [x0]; right])
  44. in (match chunk with
  45. | (x2 :: rest2) -> (true, x2 :: List.rev rest2)
  46. | [] -> raise (Failure "Fuck"))
  47. else (false, x0 :: rest1)))
  48. | [] -> (false, [])
  49. in
  50. let char_list = string_to_char_list word in
  51. match next_permutation_impl char_list with
  52. | (true, result) -> Some (char_list_to_string result)
  53. | _ -> None
  54.  
Success #stdin #stdout 0s 4212KB
stdin
Standard input is empty
stdout
Standard output is empty