2021 Day 1
Mix.install([
{:kino, "~> 0.6.1"},
{:kino_vega_lite, "~> 0.1.1"}
])
alias VegaLite, as: Vl
Input
raw_input = Kino.Input.textarea("Problem Input")
Parse
input =
Kino.Input.read(raw_input)
|> String.trim()
|> String.split("\n")
|> Enum.map(&String.to_integer/1)
Simple graph of the depth over time
{min, max} = Enum.min_max(input)
# Initialize the specification, optionally with some top-level properties
Vl.new(width: 400)
# Specify data source for the graphic using one of the data_from_* functions
|> Vl.data_from_values(depth: input, time: 0..length(input))
# Pick a visual mark
|> Vl.mark(:line)
# Map data fields to visual properties of the mark, in this case point positions
|> Vl.encode_field(:y, "depth", type: :quantitative, scale: [domain: [min, max], reverse: true])
|> Vl.encode_field(:x, "time", type: :quantitative)
Part 1
Count the number of times the depth increased
defmodule Part1 do
def count_increases(depths) do
depths
# Group into overlapping chunks of two
|> Enum.chunk_every(2, 1, :discard)
# Keep only the ones that are increases
|> Enum.filter(fn [first, second] ->
first < second
end)
# Count the remaining pairs
|> Enum.count()
end
end
Part1.count_increases(input)
Part 2
Count the the increases in a sliding three wide window of depths
input
|> Enum.chunk_every(3, 1, :discard)
|> Enum.map(&Enum.sum/1)
|> Part1.count_increases()