Solutions to Advent of Code 2018 Day 1 in Elixir and Ruby
Day 1 had a simple challenge, compute the sum of a few numbers and find out when
a prev frequency shows up again.
Part 1
Elixir
The elixir version is pretty straightforward, we create a stream using the
standard input which creates an entry per line, transform it into a number and
compute the sum:
1 2 3 4 5 6 7 8 9 10 11 12 13 14
#!/usr/bin/env elixir # run it as follows: # $ ./elixir.exs < input.txt # 484
# read each line IO.stream(:stdio, :line) |> Stream.map(fn str -> {n, ""} = str |> String.trim() |> Integer.parse() n end) |> Enum.sum() |> IO.puts()
Ruby
The ruby version is similar to the elixir version
1 2 3 4 5 6 7 8
#!/usr/bin/env ruby # run it as follows: # $ ./ruby.rb < input.txt # 484
puts ARGF.each_line .map(&:to_i) .sum
Part 2
Elixir
This was a bit tricky as you may have to repeat the input multiple times to get
the answer. To do this in elixir, we use simple recursion if we aren’t able to
find a repeating frequency in the current iteration. Also, note that we are
using a map to store previous frequencies, I have seen folks use a list which
cause a huge impact on performance as lists don’t perform well for lookups
whereas maps really shine in these scenarios.