rearrange some stuff

This commit is contained in:
Rhiannon Morris 2020-12-03 15:11:29 +01:00
parent 5c59d80e00
commit 6ac8be6984
10 changed files with 84 additions and 51 deletions

32
day1.ml
View file

@ -1,13 +1,4 @@
module IntSet = struct
include Set.Make(Int)
let exists_opt (type a) (f: int -> a option) (set: t): a option =
let exception Found of a in
let f' x = Option.iter (fun x -> raise (Found x)) (f x) in
match iter f' set with
| exception Found x -> Some x
| _ -> None
end
module IntSet = Set_ext.Make(Int)
let read_ints =
Bracket.infile_lines ~line:int_of_string ~of_seq:IntSet.of_seq
@ -23,31 +14,18 @@ let rec find ?(target=2020) ~n set =
Option.map (List.cons x) (find ~target:(target - x) ~n:(n - 1) set) in
IntSet.exists_opt joined set
let print_result xs =
let res = List.fold_left ( * ) 1 xs in
let rec print_prod fmt = function
| [] -> Format.pp_print_text fmt "{}"
| [x] -> Format.fprintf fmt "%d" x
| x::xs -> Format.fprintf fmt "%d * %a" x print_prod xs in
Format.printf "%a = %d\n" print_prod xs res
let main' n input =
match find ~n (read_ints input) with
| Some xs -> print_result xs
| Some xs -> Misc.print_prod xs
| None -> raise Not_found
let mains = [|main' 2; main' 3|]
let main = function
| [part; input] -> mains.(int_of_string part - 1) input
| _ -> Usage.exit_default 1
let main = Misc.main 1 [|main' 2; main' 3|]
let%expect_test "part 1" =
mains.(0) "../../data/day1"; (* is this always the right path??? *)
main' 2 "../../data/day1"; (* is this always the right path??? *)
[%expect{| 534 * 1486 = 793524 |}]
let%expect_test "part 2" =
mains.(1) "../../data/day1";
main' 3 "../../data/day1";
[%expect{| 71 * 686 * 1263 = 61515678 |}]