Run this notebook

Use Livebook to open this notebook and explore new ideas.

It is easy to get started, on your machine or the cloud.

Click below to open and run it in your Livebook at .

(or change your Livebook location)

<!-- vim: syntax=markdown --> # Advent 2021 - Day 3 ## Setup ```elixir Mix.install([ {:kino, github: "livebook-dev/kino"} ]) ``` ```elixir input = Kino.Input.textarea("Please paste your input file:") ``` ```elixir input = input |> Kino.Input.read() |> String.trim() |> String.split("\n") ``` ## Part 1 ```elixir epsilon = input |> Enum.reduce(nil, fn line, acc -> result_of_line = String.graphemes(line) |> Enum.map(fn char -> if char == "0" do {1, 0} else {0, 1} end end) if acc == nil do result_of_line else Enum.zip(result_of_line, acc) |> Enum.map(fn {r, a} -> {r0, r1} = r {a0, a1} = a {r0 + a0, r1 + a1} end) end end) |> Enum.map(fn {zeros, ones} -> if zeros > ones do "0" else "1" end end) {gamma, _} = epsilon |> Enum.map(fn value -> if value == "1" do "0" else "1" end end) |> Enum.join() |> Integer.parse(2) {epsilon, _} = epsilon |> Enum.join() |> Integer.parse(2) epsilon * gamma ``` ## Part 2 ```elixir defmodule Part2 do def invoke(list, index, condition) do if length(list) == 1 do List.first(list) else %{"0" => zeros, "1" => ones} = list |> Enum.reduce(%{}, fn line, acc -> char = String.graphemes(line) |> Enum.at(index) Map.update(acc, char, 1, &(&1 + 1)) end) keep = if condition.(zeros, ones), do: "0", else: "1" list = Enum.filter(list, fn line -> String.graphemes(line) |> Enum.at(index) == keep end) invoke(list, index + 1, condition) end end end oxygen_generator = Part2.invoke(input, 0, fn zeros, ones -> zeros > ones end) c02_scrubber = Part2.invoke(input, 0, fn zeros, ones -> zeros <= ones end) (Integer.parse(oxygen_generator, 2) |> elem(0)) * (Integer.parse(c02_scrubber, 2) |> elem(0)) ```
See source

Have you already installed Livebook?

If you already installed Livebook, you can configure the default Livebook location where you want to open notebooks.
Livebook up Checking status We can't reach this Livebook (but we saved your preference anyway)
Run notebook

Not yet? Install Livebook in just a minute

Livebook is open source, free, and ready to run anywhere.

Run on your machine

with Livebook Desktop

Run in the cloud

on select platforms

To run on Linux, Docker, embedded devices, or Elixir’s Mix, check our README.

PLATINUM SPONSORS
SPONSORS
Code navigation with go to definition of modules and functions Read More ×