67 lines
1.3 KiB
OCaml
67 lines
1.3 KiB
OCaml
open Containers
|
|
|
|
let lines_of_input day =
|
|
let base_path =
|
|
match Inputs.Sites.inputs with
|
|
| path :: _ -> path
|
|
| _ -> failwith "cant find path containing inputs"
|
|
in
|
|
let path = Printf.sprintf "%s/day%d.tt" base_path day in
|
|
IO.(with_in path read_lines_l)
|
|
;;
|
|
|
|
(** [f] in [memo f] should be a function that makes recursive calls
|
|
via the memoized function passed as its first argument. ie:
|
|
{[
|
|
let fib_m =
|
|
memo (fun self x ->
|
|
match x with
|
|
| 0 | 1 -> 1
|
|
| x -> self (x - 1) + self (x - 2))
|
|
;;
|
|
]} *)
|
|
let memo f =
|
|
let open Hashtbl in
|
|
let cache = create 1000 in
|
|
let rec f_mem k =
|
|
try find cache k with
|
|
| Not_found ->
|
|
let v = f f_mem k in
|
|
add cache k v;
|
|
v
|
|
in
|
|
f_mem
|
|
;;
|
|
|
|
let%expect_test "fib memoized" =
|
|
let fib_m =
|
|
memo (fun fib_m x ->
|
|
match x with
|
|
| 0 | 1 -> 1
|
|
| x -> fib_m (x - 1) + fib_m (x - 2))
|
|
in
|
|
Printf.printf "%i\n" @@ fib_m 100;
|
|
[%expect {| 1298777728820984005 |}]
|
|
;;
|
|
|
|
module Parse = struct
|
|
include Angstrom
|
|
|
|
let sign = option 1 (char '-' >>= fun _ -> return (-1))
|
|
|
|
let digits =
|
|
take_while1 (function
|
|
| '0' .. '9' -> true
|
|
| _ -> false)
|
|
>>| int_of_string
|
|
;;
|
|
|
|
let int = map2 sign digits ~f:( * )
|
|
|
|
let not_int =
|
|
skip_while (function
|
|
| '0' .. '9' | '-' -> false
|
|
| _ -> true)
|
|
;;
|
|
end
|