Powered by AppSignal & Oban Pro
Would you like to see your link here? Contact us

Day 7

advent_of_code/2021/day-07.livemd

Day 7

Setup

Mix.install([
  {:kino, "~> 0.5.0"}
])
input = Kino.Input.text("Please paste your input:")
line =
  input
  |> Kino.Input.read()
  |> String.split(",")
  |> Enum.map(&String.to_integer/1)

Part 1

{min, max} = Enum.min_max(line)

min..max
|> Enum.map(fn i ->
  line |> Enum.map(fn j -> abs(j - i) end) |> Enum.sum()
end)
|> Enum.min()
sorted = Enum.sort(line)
pos = div(length(line), 2)

# The answer will be in the median
sorted
|> Enum.slice(pos, 2)
|> Enum.map(fn i ->
  Enum.map(line, fn j -> abs(j - i) end) |> Enum.sum()
end)
|> Enum.min()

Part 2

{min, max} = Enum.min_max(line)

min..max
|> Enum.map(fn i ->
  line
  |> Enum.map(fn j ->
    n = abs(j - i)
    n * (n + 1) / 2
  end)
  |> Enum.sum()
end)
|> Enum.min()
n = Enum.sum(line) / length(line)

# The answer will be in the mean
floor(n)..ceil(n)
|> Enum.map(fn i ->
  line
  |> Enum.map(fn j ->
    n = abs(j - i)
    n * (n + 1) / 2
  end)
  |> Enum.sum()
end)
|> Enum.min()

???

Kino.animate(300, true, fn
  true ->
    spaces = String.duplicate(" ", Enum.random(0..8))

    {:cont,
     Kino.Markdown.new(~s"""
     ```
     #{spaces}(||) (^,,,,°) (\\/)
     ```
     """), false}

  false ->
    spaces = String.duplicate(" ", Enum.random(0..8))

    {:cont,
     Kino.Markdown.new(~s"""
     ```
     #{spaces}(\\/) (°,,,,^) (||)
     ```
     """), true}
end)