re: AoC Day 1: Chronal Calibration VIEW POST

FULL DISCUSSION
 

I'm doing this in C++ this year, but as we are proposing original solutions with very expressive languages, I'll show a solution in OCaml :)

OCaml

Part 1

let rec f freq ic =
  try f (freq + int_of_string (input_line ic)) ic
  with End_of_file -> freq

let () = Printf.printf "%d\n" (f 0 stdin)

Part 2

let rec read_changes changes ic =
  let next_line = try Some (input_line ic) with End_of_file -> None in
  match next_line with
  | None -> List.rev changes
  | Some c -> read_changes (int_of_string c :: changes) ic

let rec f freq freqs changes_done = function
  | [] -> f freq freqs [] (List.rev changes_done)
  | c :: r ->
    let freq' = freq + c in
    if List.mem freq' freqs then freq'
    else f freq' (freq' :: freqs) (c :: changes_done) r

let () = Printf.printf "%d\n" (f 0 [0] [] (read_changes [] stdin))

Using lists is not very efficient but the code is quite short, that is nice.

code of conduct - report abuse