summary refs log tree commit diff stats
path: root/day6.ml
diff options
context:
space:
mode:
authorBrian Chu <brianmchu42@gmail.com>2022-02-14 14:47:31 -0800
committerBrian Chu <brianmchu42@gmail.com>2022-02-14 14:47:31 -0800
commitd520f8941d8fb63e70d19ea5bbc9246641ef7593 (patch)
tree59485b4e0737153c4a26093fe0127b413ae6d3aa /day6.ml
parent45a68a69c63e5c329a19c6fce47e1315504ea76d (diff)
downloadAdventOfCode2017-d520f8941d8fb63e70d19ea5bbc9246641ef7593.tar.gz
solutions up to day 9
Diffstat (limited to 'day6.ml')
-rw-r--r--day6.ml41
1 files changed, 41 insertions, 0 deletions
diff --git a/day6.ml b/day6.ml
new file mode 100644
index 0000000..10d5e63
--- /dev/null
+++ b/day6.ml
@@ -0,0 +1,41 @@
+#use "topfind";;
+#thread;;
+#require "core";;
+#require "stdio";;
+
+open Core
+open Stdio
+
+let memory = In_channel.read_all "day6.txt"
+             |> String.strip |> String.split ~on:'\t'
+             |> Array.of_list |> Array.map ~f:int_of_string
+
+let len = Array.length memory
+let seen = Caml.Hashtbl.create 5000
+
+let array_max xs =
+  let f index (maxInd, maxVal) value =
+    if value > maxVal then (index, value) else (maxInd, maxVal) in
+  Array.foldi ~init:(0, 0) ~f:f xs
+
+let rec redist xs n i =
+  match n with
+  | 0 -> ()
+  | _ ->
+     let pos = (i + 1) mod len in
+     xs.(pos) <- xs.(pos) + 1;
+     redist xs (n-1) pos
+
+let rec cycle count banks =
+  match Caml.Hashtbl.find_opt seen banks with
+  | Some x ->
+     Printf.printf "%d\n" count;
+     Printf.printf "%d\n" (count - x)
+  | None ->
+     Caml.Hashtbl.add seen (Array.copy banks) count;
+     let mi, mv = array_max banks in
+     banks.(mi) <- 0;
+     redist banks mv mi;
+     cycle (count+1) banks
+
+let () = cycle 0 memory