Skip to content

Commit

Permalink
Clean up
Browse files Browse the repository at this point in the history
  • Loading branch information
drewolson committed Dec 11, 2023
1 parent 2e5d618 commit 4201724
Showing 1 changed file with 10 additions and 22 deletions.
32 changes: 10 additions & 22 deletions lib/year2023/day11.ml
Original file line number Diff line number Diff line change
Expand Up @@ -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
;;
Expand All @@ -34,29 +30,22 @@ 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

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
;;
Expand All @@ -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
Expand Down

0 comments on commit 4201724

Please sign in to comment.