day 8 complete !

This commit is contained in:
ryan committed 2023-10-01 01:55:36 -07:00
1 parent b7aabdedcb
commit 7d6b43ba93
3 files changed
+197 -1

No files matched your search

+96
View File
@@ -0,0 +1,96 @@
open Containers
module Vec2 : sig
type t
val directions : t list
val of_tuple : int * int -> t
val to_tuple : t -> int * int
val ( + ) : t -> t -> t
val at : 'a array array -> t -> 'a option
end = struct
type t = int * int
let directions = [ 1, 0; 0, 1; -1, 0; 0, -1 ]
let of_tuple x = x
let to_tuple x = x
let ( + ) a b = Pair.map_same2 ( + ) a b
let at grid point =
let x, y = to_tuple point in
let open Option in
let* row = Array.get_safe grid y in
Array.get_safe row x
;;
end
let parse_grid () =
let lines = Utils.lines_of_input 8 in
lines
|> Array.of_list
|> Array.map
Fun.(String.to_seq %> Seq.map (Char.to_string %> int_of_string) %> Seq.to_array)
;;
let rec find_taller_tree grid start_height start step =
let next = Vec2.(start + step) in
match Vec2.at grid next with
| Some height when height < start_height -> find_taller_tree grid start_height next step
| opt -> opt
;;
let part1 () =
let grid = parse_grid () in
let grid_h = Array.length grid in
let grid_w = Array.length grid.(0) in
let num_visible = ref 0 in
for y = 0 to grid_h - 1 do
for x = 0 to grid_w - 1 do
let start = Vec2.of_tuple (x, y) in
let height = Option.get_exn_or "unreachable" @@ Vec2.at grid start in
let visible =
Vec2.directions
|> List.map @@ find_taller_tree grid height start
|> List.map Option.is_none
|> List.reduce_exn ( || )
in
if visible then incr num_visible
done
done;
!num_visible
;;
let rec trees_in_view grid start start_height in_view step =
let next = Vec2.(start + step) in
match Vec2.at grid next with
| Some height when height < start_height ->
trees_in_view grid next start_height (in_view + 1) step
| Some _ -> in_view + 1
| None -> in_view
;;
let part2 () =
let grid = parse_grid () in
let grid_h = Array.length grid in
let grid_w = Array.length grid.(0) in
let best_score = ref 0 in
for y = 0 to grid_h - 1 do
for x = 0 to grid_w - 1 do
let start = Vec2.of_tuple (x, y) in
let height = Option.get_exn_or "unreachable" @@ Vec2.at grid start in
let score =
Vec2.directions
|> List.map @@ trees_in_view grid start height 0
|> List.reduce_exn ( * )
in
if score > !best_score then best_score := score
done
done;
!best_score
;;
let print () =
Printf.(
printf "Day 8.1: %d\n" @@ part1 ();
printf "Day 8.2: %d\n" @@ part2 ())
;;