solve_1.ml 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  1. open Stdio
  2. let input =
  3. let line = In_channel.input_line In_channel.stdin in
  4. match line with
  5. | None -> ""
  6. | Some x -> x
  7. ;;
  8. let expand dm =
  9. let rec aux i acc=
  10. if (i >= String.length dm) then
  11. acc
  12. else (if (i == String.length dm -1)
  13. then
  14. let id = (i/2) in
  15. let file_size = (int_of_char dm.[i] - int_of_char '0') in
  16. let new_encoding = List.init file_size (fun _ -> id) in
  17. new_encoding@acc
  18. else
  19. let id = (i/2) in
  20. let file_size = (int_of_char dm.[i] - int_of_char '0') in
  21. let empty_space = (int_of_char dm.[i+1] - int_of_char '0') in
  22. let new_encoding = (List.init empty_space (fun _ -> -1)) @ (List.init file_size (fun _ -> id)) in
  23. aux (i+2) (new_encoding@acc))
  24. in
  25. aux 0 []
  26. ;;
  27. let reverse_list =
  28. let rec aux acc = function
  29. | [] -> acc
  30. | x :: tl -> aux (x::acc) tl
  31. in
  32. aux []
  33. ;;
  34. let get_dm_and_queue =
  35. let rec aux acc queue = function
  36. | [] -> acc, (reverse_list queue)
  37. | -1 :: tl -> aux (-1::acc) queue tl
  38. | x :: tl -> aux (x::acc) (x::queue) tl
  39. in
  40. aux [] []
  41. ;;
  42. let compact dm =
  43. let reversed, queue = (get_dm_and_queue dm) in
  44. let len_dm = (List.length queue) in
  45. let rec aux acc q l=
  46. if (List.length acc == len_dm) then (reverse_list acc) else
  47. match l with
  48. | [] -> (reverse_list acc)
  49. | -1::tl -> aux ((List.hd q)::acc) (List.tl q) tl
  50. | x :: tl -> aux (x::acc) q tl
  51. in
  52. aux [] queue reversed
  53. ;;
  54. let calculate_checksum dm=
  55. let rec aux id accum = function
  56. | [] -> accum
  57. | x::tl -> aux (id+1) (id*x + accum) tl
  58. in
  59. aux 0 0 dm;;
  60. let solve =
  61. let dm = expand input in
  62. calculate_checksum (compact dm);
  63. ;;
  64. let () =
  65. printf "Total: %d\n" solve;;