Skip to content

Commit

Permalink
2021.03
Browse files Browse the repository at this point in the history
  • Loading branch information
Doruk Gurleyen committed Dec 3, 2021
1 parent 3ecbb09 commit 2195048
Show file tree
Hide file tree
Showing 7 changed files with 7,474 additions and 7 deletions.
1 change: 1 addition & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -1 +1,2 @@
node_modules
.vscode/settings.json
3 changes: 0 additions & 3 deletions .vscode/settings.json

This file was deleted.

47 changes: 47 additions & 0 deletions challenges/2021/03.exs
Original file line number Diff line number Diff line change
@@ -0,0 +1,47 @@
Code.compile_file(Path.join([__ENV__.file], ["../../../utils/utils.exs"]))

defmodule Challenge do
@moduledoc false

def first_result(input) do
bit_counts =
input
|> Enum.reduce(
%{},
fn line, acc ->
line
|> String.split("", trim: true)
|> Enum.with_index()
|> Enum.reduce(acc, fn y, acc2 ->
idx = elem(y, 1)
bit = String.to_integer(elem(y, 0))

Map.update(
acc2,
idx,
[0, 0],
fn counts -> List.update_at(counts, bit, &(&1 + 1)) end
)
end)
end
)

gamma =
Enum.map(0..(map_size(bit_counts) - 1), fn idx ->
[count_zero, count_one] = get_in(bit_counts, [idx])
if count_zero > count_one, do: "0", else: "1"
end)

epsilon =
Enum.map(gamma, fn
"0" -> "1"
"1" -> "0"
end)

int(gamma) * int(epsilon)
end

defp int(bits), do: bits |> Enum.join() |> String.to_integer(2)
end

Utils.run(&Challenge.first_result/1, __ENV__.file, "Q1")
27 changes: 27 additions & 0 deletions challenges/2021/03.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
// Part 2
const solvePuzzle = (input) => {
input = input.split("\n");
return find(input, "O2") * find(input, "CO2");
};

const find = (input, measure, currIdx = 0) => {
const mostFrequentBits = getMostFrequentBits(input);

input = input.filter((str) =>
measure === "O2" ? str[currIdx] === mostFrequentBits[currIdx] : str[currIdx] !== mostFrequentBits[currIdx]
);

return input.length <= 1 ? Number.parseInt(input[0], 2) : find(input, measure, currIdx + 1);
};

const getMostFrequentBits = (input) => {
const frequencies = Array.from({ length: input[0].length }, () => [0, 0]);

input.forEach((line) =>
line.split("").forEach((bit, bitidx) => (frequencies[bitidx][bit] = frequencies[bitidx][bit] + 1))
);

return frequencies.map(([count0, count1]) => (count0 > count1 ? "0" : "1"));
};

require(__dirname + "/../../utils/test.js").test(__filename, __dirname, solvePuzzle);
Loading

0 comments on commit 2195048

Please sign in to comment.