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)

# Advent of Code 2024/7 ```elixir Mix.install([ {:kino, "~> 0.14.2"} ]) ``` ## Section ```elixir input = Kino.Input.textarea("input") ``` ```elixir defmodule AoC2024_7 do def parse(input) do Kino.Input.read(input) |> String.split("\n\n", trim: true) |> Enum.map(fn part -> String.split(part, "\n", trim: true) |> Enum.map(fn row -> row_parser(row) end) end) |> Enum.at(0) end def row_parser(row) do [result, parts] = String.split(row, ":", trim: true) {String.split(parts, " ", trim: true) |> Enum.map(fn part -> String.to_integer(part) end), String.to_integer(result)} end def step(list, operators \\ ["+", "*"]) def step([element | []], _operators), do: [[element]] def step([element | rest], operators) do step(rest, operators) |> Enum.flat_map(fn path -> Enum.map(operators, fn operator -> [element, operator] ++ path end) end) end def split_by_cocatenation(list) do list |> Enum.chunk_by(fn x -> x == "||" end) |> Enum.reject(fn x -> x == ["||"] end) end def calculate_position(item, acc, "+"), do: acc + item def calculate_position(item, acc, "*"), do: acc * item def calculate_position(item, acc, "||"), do: String.to_integer(Enum.join([acc, item])) def calculate(list) do tl(list) |> Enum.chunk_every(2) |> Enum.reduce(hd(list), fn [op, item], acc -> calculate_position(item, acc, op) end) end def check_row({parts, result}, operators \\ ["+", "*"]) do Enum.any?(step(parts, operators), fn el -> calculate(el) == result end) end def part_1(input) do input |> parse |> Enum.filter(fn row -> check_row(row) end) |> Enum.map(fn row -> elem(row, 1) end) |> Enum.sum end def part_2(input) do input |> parse |> Enum.filter(fn row -> check_row(row, ["+", "*", "||"]) end) |> Enum.map(fn row -> elem(row, 1) end) |> Enum.sum end end ``` ```elixir AoC2024_7.part_1(input) ``` ```elixir AoC2024_7.part_2(input) ```
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 ×