Created
December 14, 2020 13:33
-
-
Save ynonp/993309f0cb751830dcc32aa5c24afa49 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
defmodule VM14 do | |
use Bitwise | |
defstruct [:memory, :mask_bits_for_and, :mask_values_for_or] | |
def new do | |
%VM14{memory: %{}, mask_bits_for_and: 0, mask_values_for_or: 0, mask_str: "0"} | |
end | |
def update_mask(vm, mask_str) do | |
mask_bits_for_and = mask_str | |
|> String.replace(~r/[01]/, "0") | |
|> String.replace(~r/X/, "1") | |
|> String.to_integer(2) | |
mask_values_for_or = mask_str | |
|> String.replace(~r/X/, "0") | |
|> String.to_integer(2) | |
Map.merge(vm, | |
%{ | |
:mask_str => mask_str, | |
:mask_bits_for_and => mask_bits_for_and, | |
:mask_values_for_or => mask_values_for_or, | |
} | |
) | |
end | |
def apply_address_mask(vm, address) do | |
end | |
def apply_mask(vm, value) do | |
(value &&& vm.mask_bits_for_and) ||| vm.mask_values_for_or | |
end | |
end | |
defmodule Day14 do | |
def read_input do | |
File.read!("input/day14.txt") | |
|> String.split("\n", trim: true) | |
|> Enum.map(&(String.split(&1, " = ", trim: true))) | |
end | |
def process(["mask", mask], vm) do | |
VM14.update_mask(vm, mask) | |
end | |
def process([command, value], vm) do | |
where = Regex.scan(~r/\[(\d+)\]/, command) | |
|> Enum.at(0) | |
|> Enum.at(1) | |
masked_value = VM14.apply_mask(vm, String.to_integer(value)) | |
Map.update!(vm, :memory, fn memory -> | |
Map.put(memory, where, masked_value) | |
end) | |
end | |
def part1 do | |
read_input() | |
|> Enum.reduce(VM14.new, &process/2) | |
|> Map.get(:memory) | |
|> Map.values | |
|> Enum.sum | |
|> IO.inspect | |
end | |
end | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment