From ccf4847c2b46dc505e1d49b444ca8e06bbe4de4b Mon Sep 17 00:00:00 2001 From: Matthew Gretton-Dann Date: Sat, 14 Dec 2024 08:16:22 +0000 Subject: [PATCH] 2024 day 14 part 1 --- bin/day2414.ml | 51 ++++++++++++++++++++++++++++++++++++++++++++++++++ bin/dune | 6 ++++-- 2 files changed, 55 insertions(+), 2 deletions(-) create mode 100644 bin/day2414.ml diff --git a/bin/day2414.ml b/bin/day2414.ml new file mode 100644 index 0000000..c69664f --- /dev/null +++ b/bin/day2414.ml @@ -0,0 +1,51 @@ +module IntMap = Map.Make (Int) + +let parse_robot s = + let re = + Str.regexp {|p=\(-?[0-9]+\),\(-?[0-9]+\) v=\(-?[0-9]+\),\(-?[0-9]+\)|} + in + let _ = Str.search_forward re s 0 in + ( ( int_of_string (Str.matched_group 1 s), + int_of_string (Str.matched_group 2 s) ), + ( int_of_string (Str.matched_group 3 s), + int_of_string (Str.matched_group 4 s) ) ) + +let parse_robots = List.map parse_robot +let robots_of_file fname = Aoc.strings_of_file fname |> parse_robots +let width = 101 +let height = 103 +let secs = 100 + +let normalize_velocity (p, (dx, dy)) = + (p, ((dx + width) mod width, (dy + height) mod height)) + +let calc_pos_after secs ((x, y), (dx, dy)) = + let x' = (x + (secs * dx)) mod width in + let y' = (y + (secs * dy)) mod height in + (x', y') + +let in_a_quadrant (x, y) = x <> width / 2 && y <> height / 2 +let update_count = function None -> Some 1 | Some x -> Some (x + 1) + +let get_quadrant (x, y) = + if x < width / 2 && y < height / 2 then 1 + else if x > width / 2 && y < height / 2 then 2 + else if x < width / 2 && y > height / 2 then 4 + else if x > width / 2 && y > height / 2 then 3 + else failwith "get_quadrant" + +let loc_counts map p = + let idx = get_quadrant p in + IntMap.update idx update_count map + +let part robots = + let counts = + robots + |> List.map normalize_velocity + |> List.map (calc_pos_after secs) + |> List.filter in_a_quadrant + |> List.fold_left loc_counts IntMap.empty + in + IntMap.fold (fun _ v acc -> acc * v) counts 1 + +let _ = Aoc.main robots_of_file [ (string_of_int, part) ] diff --git a/bin/dune b/bin/dune index c984710..8bdfd57 100644 --- a/bin/dune +++ b/bin/dune @@ -12,7 +12,8 @@ day2410 day2411 day2412 - day2413) + day2413 + day2414) (names day2401 day2402 @@ -26,5 +27,6 @@ day2410 day2411 day2412 - day2413) + day2413 + day2414) (libraries str aoc))