summary refs log tree commit diff stats
path: root/day1.ml
blob: 6e95cfb3fa6d05d9dd0d0038695a9a7bb6c05f89 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
#use "topfind";;
#thread;;
#require "core";;
#require "stdio";;

open Core
open Stdio

let captcha = In_channel.read_all "day1.txt"
              |> String.strip
              |> String.to_list
              |> List.map ~f:(fun x -> Char.to_int x - Char.to_int '0')

let rec last = function
  | [] -> assert false
  | [x] -> x
  | x::xs -> last xs

let rec init = function
  | [] -> []
  | [x] -> []
  | x::xs -> x::(init xs)

let rotate_once l = (last l)::(init l)

let rec rotate n l =
  match n with
  | 0 -> l
  | _ -> rotate (n-1) (rotate_once l)

let neighbor_sums n l =
  let rotated = rotate n l in
    Caml.List.combine l rotated
    |> List.map ~f:(fun (x, y) -> if x = y then x else 0)
    |> List.fold_left ~f:(+) ~init:0

let () =
  neighbor_sums 1 captcha |> Printf.printf "%d\n";
  neighbor_sums ((List.length captcha) / 2) captcha |> Printf.printf "%d\n"