Move IntPair and PosSet into Aoc library.

These are obviously generic enough and useful for the future that they
can be moved to a shared library.
This commit is contained in:
2024-12-06 17:15:37 +00:00
parent 38d0781c7e
commit 831bbf4f63
3 changed files with 75 additions and 19 deletions

View File

@@ -1,16 +1,4 @@
(** [IntPair] is a module describing pairs of ints, suitable for using with
[Set.Make]. *)
module IntPair = struct
type t = int * int
let compare (x, y) (x', y') =
match compare y y' with 0 -> compare x x' | c -> c
end
module PosSet = Set.Make (IntPair)
(** [PosSet] represents a set of positions. *)
type map = { blocks : PosSet.t; width : int; height : int }
type map = { blocks : Aoc.IntPairSet.t; width : int; height : int }
(** [map] represents a map with [blocks] and a [width] and [height]. *)
(** [find_start strs] returns the location [(x, y)] of the starting position. *)
@@ -29,14 +17,14 @@ let find_start strs =
let map_of_strings strs =
let rec row_scan acc y pos s =
match String.index_from_opt s pos '#' with
| Some x -> row_scan (PosSet.add (x, y) acc) y (x + 1) s
| Some x -> row_scan (Aoc.IntPairSet.add (x, y) acc) y (x + 1) s
| None -> acc
in
let rec impl acc y = function
| h :: t -> impl (row_scan acc y 0 h) (y + 1) t
| [] -> (acc, y)
in
let blocks, height = impl PosSet.empty 0 strs in
let blocks, height = impl Aoc.IntPairSet.empty 0 strs in
let width = String.length (List.hd strs) in
{ blocks; height; width }
@@ -62,7 +50,7 @@ let is_valid_pos map (x, y) =
the updated [(pos, vel)] pair. *)
let rec move map ((x, y), (dx, dy)) =
let x', y' = (x + dx, y + dy) in
if PosSet.mem (x', y') map.blocks then move map ((x, y), (-dy, dx))
if Aoc.IntPairSet.mem (x', y') map.blocks then move map ((x, y), (-dy, dx))
else ((x', y'), (dx, dy))
(** [walk_map map (pos, vel)] walks around [map] starting at [pos] moving in the
@@ -97,15 +85,15 @@ let has_cycles map (pos, vel) =
let walk_block map (pos, vel) bpos =
if bpos = pos then false
else
let map' = { map with blocks = PosSet.add bpos map.blocks } in
let map' = { map with blocks = Aoc.IntPairSet.add bpos map.blocks } in
has_cycles map' (pos, vel)
let part1 (map, pos, vel) =
walk_map map (pos, vel) |> List.sort_uniq IntPair.compare |> List.length
walk_map map (pos, vel) |> List.sort_uniq Aoc.IntPair.compare |> List.length
let part2 (map, pos, vel) =
walk_map map (pos, vel)
|> List.sort_uniq IntPair.compare
|> List.sort_uniq Aoc.IntPair.compare
|> List.filter (walk_block map (pos, vel))
|> List.length