Skip to content

Instantly share code, notes, and snippets.

@adrian-goe
Created December 15, 2023 09:49
Show Gist options
  • Save adrian-goe/5b603e503b2ec7542d7f98feaa91ebce to your computer and use it in GitHub Desktop.
Save adrian-goe/5b603e503b2ec7542d7f98feaa91ebce to your computer and use it in GitHub Desktop.
Advent of Code Day 15
defmodule AoC.Hash do
def hash_calculate(input) do
input
|> String.graphemes()
|> Enum.map(fn char -> :binary.first(char) end)
|> Enum.reduce(0, fn hashvalue, acc ->
rem((acc + hashvalue) * 17, 256)
end)
end
end
defmodule AoC.Part1 do
@input Kino.FS.file_path("part1.txt")
|> File.read!()
def solve do
@input
|> String.split(",")
|> Enum.map(&AoC.Hash.hash_calculate/1)
|> Enum.sum()
end
end
AoC.Part1.solve()
defmodule AoC.Part2 do
@input Kino.FS.file_path("part1.txt")
|> File.read!()
def solve do
Enum.reduce(@input |> String.split(","), Map.new(), fn item, acc ->
[val, lense] = String.split(item, ~r/[=-]/)
key = AoC.Hash.hash_calculate(val)
value = Map.get(acc, key, [])
if item =~ ~r/=/ do
value = concat_or_replace(value, val, {val, String.to_integer(lense)})
Map.put(acc, key, value)
else
value = remove_first(value, val)
Map.put(acc, key, value)
end
end)
|> Enum.map(fn {box, items} ->
items
|> Enum.with_index(1)
|> Enum.map(fn {{_val, lense}, index} ->
(box + 1) * index * lense
end)
|> Enum.sum()
end)
|> Enum.sum()
end
def concat_or_replace(list, key, value) do
index =
Enum.find_index(list, fn {list_key, _val} ->
list_key == key
end)
if index != nil do
List.replace_at(list, index, value)
else
list ++ [value]
end
end
def remove_first(list, value) do
index =
Enum.find_index(list, fn {key, _val} ->
key == value
end)
if index != nil do
List.delete_at(list, index)
else
list
end
end
end
AoC.Part2.solve()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment