From 420172476c996144d82138f32a0288983789b64c Mon Sep 17 00:00:00 2001 From: drew Date: Mon, 11 Dec 2023 09:13:50 -0600 Subject: [PATCH] Clean up --- lib/year2023/day11.ml | 32 ++++++++++---------------------- 1 file changed, 10 insertions(+), 22 deletions(-) diff --git a/lib/year2023/day11.ml b/lib/year2023/day11.ml index 0e8b91d..7bfaef0 100644 --- a/lib/year2023/day11.ml +++ b/lib/year2023/day11.ml @@ -2,27 +2,23 @@ module Coord = struct type t = int * int [@@deriving equal, compare, sexp] end -module CoordPair = struct - type t = Coord.t * Coord.t [@@deriving equal, compare, sexp] -end - module IntMap = Map.Make (Int) module CoordMap = Map.Make (Coord) -module CoordPairSet = Set.Make (CoordPair) let parse input = input |> String.split_lines |> List.map ~f:String.to_list let expand amount galaxy = + let open Z in let x_counts = galaxy |> List.transpose_exn |> List.mapi ~f:(fun i line -> - i, if List.for_all line ~f:(Char.equal '.') then amount else 1) + i, if List.for_all line ~f:(Char.equal '.') then ~$amount else ~$1) in let y_counts = galaxy |> List.mapi ~f:(fun i line -> - i, if List.for_all line ~f:(Char.equal '.') then amount else 1) + i, if List.for_all line ~f:(Char.equal '.') then ~$amount else ~$1) in IntMap.of_alist_exn x_counts, IntMap.of_alist_exn y_counts ;; @@ -34,16 +30,11 @@ let to_grid galaxy = ;; let pairs grid = - let stars = grid |> Map.filter ~f:(Char.equal '#') |> Map.keys in - stars - |> List.concat_map ~f:(fun a -> - List.filter_map stars ~f:(fun b -> - if Coord.equal a b - then None - else if Coord.compare a b < 0 - then Some (a, b) - else Some (b, a))) - |> CoordPairSet.of_list + let rec all_pairs = function + | a :: rest -> List.map rest ~f:(fun b -> a, b) @ all_pairs rest + | [] -> [] + in + grid |> Map.filter ~f:(Char.equal '#') |> Map.keys |> all_pairs ;; let range a b = if a < b then List.range a b else List.range b a @@ -51,12 +42,10 @@ let range a b = if a < b then List.range a b else List.range b a let distance x_counts y_counts ((x1, y1), (x2, y2)) = let open Z in let x_dist = - range x1 x2 - |> List.fold ~init:Z.zero ~f:(fun sum x -> ~$(Map.find_exn x_counts x) + sum) + range x1 x2 |> List.fold ~init:~$0 ~f:(fun sum x -> Map.find_exn x_counts x + sum) in let y_dist = - range y1 y2 - |> List.fold ~init:Z.zero ~f:(fun sum y -> ~$(Map.find_exn y_counts y) + sum) + range y1 y2 |> List.fold ~init:~$0 ~f:(fun sum y -> Map.find_exn y_counts y + sum) in x_dist + y_dist ;; @@ -67,7 +56,6 @@ let solve amount input = galaxy |> to_grid |> pairs - |> Set.to_list |> List.map ~f:(distance x_counts y_counts) |> List.fold ~init:Z.zero ~f:Z.add |> Z.to_string