solve_2.ml 1.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445
  1. open Stdio
  2. open Str
  3. let rec construct_list l1=
  4. let line = In_channel.input_line In_channel.stdin in
  5. match line with
  6. | None -> l1
  7. | Some x -> let report = List.map int_of_string (Str.split (regexp {| |}) x) in
  8. construct_list (report::l1)
  9. ;;
  10. let monotony a b = if ((abs (a - b)) < 4) then
  11. (if (a < b) then "increasing" else
  12. (if (a > b) then "decreasing" else "ko"))
  13. else "ko"
  14. ;;
  15. let rec is_safe status tolerance l =
  16. (Printf.printf "%s %d\n" status tolerance);
  17. if (tolerance < 0) then false else
  18. (match status with
  19. | "ko" -> is_safe "init" (tolerance - 1) l
  20. | "increasing" -> (match l with
  21. | a :: b :: tl -> if ((monotony a b) == "increasing") then (is_safe "increasing" tolerance (b::tl)) else (is_safe "increasing" (tolerance-1) (b::tl))
  22. | _ :: [] | [] -> true)
  23. | "decreasing" -> (match l with
  24. | a :: b :: tl -> if ((monotony a b) == "decreasing") then (is_safe "decreasing" tolerance (b::tl)) else (is_safe "decreasing" (tolerance-1) (b::tl))
  25. | _ :: [] | [] -> true)
  26. | "init" -> (match l with
  27. | a :: b :: tl -> is_safe (monotony a b) tolerance (b::tl)
  28. | _ :: [] | [] -> true)
  29. | _ -> true )
  30. ;;
  31. let rec solve accum = function
  32. | hd :: tl -> (Printf.printf "%d\n" (List.hd hd)); if (is_safe "init" 1 hd) then solve (accum + 1) tl else solve accum tl
  33. | [] -> accum
  34. ;;
  35. let () =
  36. let li = construct_list [] in
  37. printf "Total: %d\n" (solve 0 li)