summary refs log tree commit diff stats
path: root/day4.ml
blob: e058aec064d9f4e2ddf336f9c626032b2bb923ed (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
#use "topfind";;
#thread;;
#require "core";;
#require "stdio";;

open Core
open Stdio

let passphrases = In_channel.read_lines "day4.txt"
                  |> List.map ~f:(fun x -> String.strip x |> String.split ~on:' ')


let passphrase_set_lengths p =
  let toSet strings =
    List.fold ~f:Set.add ~init:(Set.empty (module String)) strings in
  List.map ~f:toSet p |> List.map ~f:Set.length

let passphrase_lengths = List.map ~f:List.length

let rec has_anagram passphrase =
  let string_to_set =
    String.fold ~f:Set.add ~init:(Set.empty (module Char)) in
  let anagram a b =
    Set.equal (string_to_set a) (string_to_set b) in
  match passphrase with
  | [] -> false
  | h::t ->
     match List.find t ~f:(anagram h) with
     | Some x -> true
     | None -> has_anagram t

let () =
  let pairs = List.zip_exn (passphrase_set_lengths passphrases) (passphrase_lengths passphrases) in
  let valid_count = List.fold ~f:(fun acc (x, y) -> if x = y then acc+1 else acc) ~init:0 pairs in
  Printf.printf "%d\n" valid_count;

  let anagram_count = List.fold ~f:(fun acc x -> if has_anagram x then acc else acc + 1) ~init:0 passphrases in
  Printf.printf "%d\n" anagram_count