aoc2020/day2.ml

42 lines
1.1 KiB
OCaml

let parse_line' f str = Scanf.sscanf str "%d - %d %c : %s%!" f
type part1 = {min: int; max: int; char: char; pass: string}
let parse_line1 = parse_line'
(fun min max char pass -> {min; max; char; pass})
let count c str =
let res = ref 0 in
String.iter (fun d -> if c = d then incr res) str;
!res
let ok1 {min; max; char; pass} =
let res = count char pass in
res >= min && res <= max
type part2 = {pos1: int; pos2: int; char: char; pass: string}
let parse_line2 = parse_line'
(fun pos1 pos2 char pass -> {pos1 = pos1 - 1; pos2 = pos2 - 1; char; pass})
let ok2 {pos1; pos2; char; pass} =
(pass.[pos1] = char) <> (pass.[pos2] = char)
let main' ~line ~ok input =
let count_all = ref 0 in
let count_ok = ref 0 in
let check l = incr count_all; if ok l then incr count_ok in
Bracket.infile_iter_lines input ~line ~iter:check;
Printf.printf "%d out of %d ok\n" !count_ok !count_all
let main1 = main' ~line:parse_line1 ~ok:ok1
let main2 = main' ~line:parse_line2 ~ok:ok2
let mains = [|main1; main2|]
let main = function
| [part; input] -> mains.(int_of_string part - 1) input
| _ -> Usage.exit "2 <part> <infile>"