day-01-02.sml 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364
  1. (* open IntInf; *)
  2. fun read file =
  3. let
  4. val inStream = TextIO.openIn file
  5. in
  6. (* TextIO.inputAll returns a TextIO.vector, which is a string. *)
  7. TextIO.inputAll inStream
  8. end;
  9. fun count_increases [] = 0
  10. | count_increases [n] = 0
  11. | count_increases measurements =
  12. let
  13. val (first_measurement::rest_measurements) = measurements;
  14. fun iter (remaining, previous, accumulated) =
  15. if List.null remaining
  16. then
  17. accumulated
  18. else
  19. let
  20. val (current::rest) = remaining;
  21. in
  22. if current > previous
  23. then
  24. iter (rest, current, accumulated + 1)
  25. else
  26. iter (rest, current, accumulated)
  27. end
  28. in
  29. iter (rest_measurements, first_measurement, 0)
  30. end;
  31. fun sliding_window_values nil window_size = []
  32. | sliding_window_values measurements window_size =
  33. let
  34. fun calc_window (nil, window_size, sum) = sum
  35. | calc_window ((m::ms), window_size, sum) =
  36. if window_size = 0
  37. then sum
  38. else calc_window (ms, window_size - 1, sum + m);
  39. fun iter nil = []
  40. | iter (measurements as (m::ms)) =
  41. (calc_window (measurements, window_size, 0)) :: (iter ms);
  42. in
  43. iter measurements
  44. end;
  45. val str = read "input";
  46. val lines = String.tokens (fn c => c = #"\n") str;
  47. val measurements = map (fn num_as_str =>
  48. case Int.fromString num_as_str of
  49. SOME number => number
  50. | NONE =>
  51. raise Fail "encountered a non-int string")
  52. lines;
  53. count_increases (sliding_window_values measurements 3);