solved day 3 !

This commit is contained in:
ryan committed 2023-09-22 15:15:36 -07:00
1 parent 661cdf1c95
commit 6a276c3c1b
2 files changed
+358

No files matched your search

+58
View File
@@ -0,0 +1,58 @@
open Containers
module CharSet = Set.Make (Char)
let set_of_string string = CharSet.of_list (String.to_list string)
let priority char =
match char with
| 'a' .. 'z' -> 1 + Char.compare char 'a'
| 'A' .. 'Z' -> 27 + Char.compare char 'A'
| _ -> failwith @@ Printf.sprintf "'%c' is not a valid item" char
;;
let parse_line line =
let half_len = String.length line / 2 in
let first_half = String.sub line 0 half_len in
let second_half = String.sub line half_len half_len in
set_of_string first_half, set_of_string second_half
;;
let part1 lines =
List.fold_left
(fun acc line ->
let first, second = parse_line line in
let item =
match CharSet.elements @@ CharSet.inter first second with
| [ item ] -> item
| _ -> failwith "sad"
in
acc + priority item)
0
lines
;;
(*
x thank you https://doc.sherlocode.com/ for helping me find Containers and its
x List.chunks and List.reduce functions
x*)
let part2 lines =
let groups = List.chunks 3 (List.map set_of_string lines) in
List.fold_left
(fun acc group ->
let item =
match CharSet.elements @@ List.reduce_exn CharSet.inter group with
| [ item ] -> item
| _ -> failwith "sad"
in
acc + priority item)
0
groups
;;
let print () =
let lines = Utils.lines_of_input 3 in
Printf.(
printf "Day 3.1: %d\n" @@ part1 lines;
printf "Day 3.2: %d\n" @@ part2 lines)
;;