main.ml 1.1 KB

123456789101112131415161718192021222324252627282930313233343536373839
  1. open Base
  2. (* load the provided filename *)
  3. let load_list filename =
  4. let open Stdio.In_channel in
  5. let lines = with_file ~f:input_lines filename
  6. in List.map ~f:Int.of_string lines
  7. (* You might notice that this isn't actually >>=: I just wanted to
  8. have a non-parenthesized foreach! *)
  9. let (>>=) list fn = let _ = List.map ~f:fn list in None
  10. let print_result = function
  11. | None -> Stdio.printf "Unable to find result\n"
  12. | Some xs ->
  13. let lst = String.concat ~sep:" * " (List.map ~f:Int.to_string xs)
  14. in Stdio.printf "Got (%s) = %d\n" lst (List.fold ~init:1 ~f:(fun x y -> x * y) xs)
  15. let part_one source =
  16. With_return.with_return (fun r ->
  17. source >>= fun a ->
  18. source >>= fun b ->
  19. if a <> b && a + b = 2020 then r.return (Some [a; b])
  20. )
  21. let part_two source =
  22. With_return.with_return (fun r ->
  23. source >>= fun a ->
  24. source >>= fun b ->
  25. source >>= fun c ->
  26. if a <> b && b <> c && a <> c && a + b + c = 2020 then r.return (Some [a; b; c])
  27. )
  28. let main() =
  29. let source = load_list "input" in
  30. print_result (part_one source);
  31. print_result (part_two source)
  32. let () = main()