day 13, first parser combinator! thx angstrom <3

This commit is contained in:
ryan committed 2023-10-30 15:37:45 -07:00
1 parent dfa2cf11a1
commit fa8970b0de
3 files changed
+535 -1

No files matched your search

+85
View File
@@ -0,0 +1,85 @@
open Containers
type packet =
| I of int
| L of packet list
[@@deriving show { with_path = false }]
let packet_of_str line =
let open Angstrom in
let int =
take_while1 (function
| '0' .. '9' -> true
| _ -> false)
>>= fun s -> return (I (int_of_string s)) <?> "int"
in
let packet =
fix (fun packet ->
let list =
char '[' *> sep_by (char ',') packet
<* char ']'
>>= fun s -> return (L s) <?> "list"
in
choice [ int; list ])
<?> "packet"
in
Result.get_or_failwith @@ parse_string ~consume:All packet line
;;
let rec is_ordered = function
| I a, I b when a = b -> None
| I a, I b -> Some (a < b)
| (I _ as a), (L _ as b) -> is_ordered (L [ a ], b)
| (L _ as a), (I _ as b) -> is_ordered (a, L [ b ])
| L [], L [] -> None
| L [], _ -> Some true
| _, L [] -> Some false
| L (a :: a_tl), L (b :: b_tl) ->
(match is_ordered (a, b) with
| None -> is_ordered (L a_tl, L b_tl)
| result -> result)
;;
let%expect_test "Day 13.1" =
let result =
Utils.lines_of_input 13
|> List.filter Fun.(not % String.is_empty)
|> List.map packet_of_str
|> List.chunks 2
|> List.mapi (fun i packets ->
match packets with
| [ a; b ] -> i + 1, is_ordered (a, b)
| _ -> failwith "List.chunks didnt work lol")
|> List.fold_left
(fun result item ->
match item with
| i, Some true -> result + i
| _, _ -> result)
0
in
Printf.printf "%i" result;
[%expect {| 6272 |}]
;;
let%expect_test "Day 13.2" =
let result =
Utils.lines_of_input 13
|> List.filter Fun.(not % String.is_empty)
|> List.append [ "[[2]]"; "[[6]]" ]
|> List.map (fun line -> line, packet_of_str line)
|> List.sort (fun (_, a) (_, b) ->
match is_ordered (a, b) with
| None -> 0
| Some true -> -1
| Some false -> 1)
|> List.mapi (fun i (line, _) -> i + 1, line)
|> List.fold_left
(fun result (i, line) ->
match line with
| "[[2]]" | "[[6]]" -> result * i
| _ -> result)
1
in
Printf.printf "%i" result;
[%expect {| 22288 |}]
;;
+1 -1
View File
@@ -1,6 +1,6 @@
(library
(name aoc)
(libraries re containers dune-site)
(libraries re containers dune-site angstrom)
(inline_tests)
(preprocess (pps
ppx_regexp