aoc2018/elixir/lib/day01.exs -rw-r--r-- 852 bytes View raw
                                                                                
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
40
41
42
43
44
45
# --- Day 1: Chronal Calibration ---
# https://adventofcode.com/2018/day/1

defmodule Day01 do
  def parse_input(input) do
    input
    |> String.split()
    |> Enum.map(&String.to_integer/1)
  end

  def part1(input) do
    input
    |> parse_input
    |> Enum.sum()
  end

  def frequencies(diffs) do
    diffs
    |> Stream.cycle()
    |> Stream.transform(0, fn i, acc ->
      {[acc + i], acc + i}
    end)
  end

  def find_repeated(frequencies) do
    Enum.reduce_while(frequencies, MapSet.new(), fn freq, set ->
      if MapSet.member?(set, freq),
        do: {:halt, freq},
        else: {:cont, MapSet.put(set, freq)}
    end)
  end

  def part2(input) do
    input
    |> parse_input
    |> frequencies
    |> find_repeated
  end
end

input = File.read!("lib/day01.in")

Day01.part1(input) |> IO.inspect()
Day01.part2(input) |> IO.inspect()