diff --git a/2021/3.test.ts b/2021/3.test.ts new file mode 100644 index 0000000..cb8aa69 --- /dev/null +++ b/2021/3.test.ts @@ -0,0 +1,23 @@ +import { assertEquals } from "https://deno.land/std@0.116.0/testing/asserts.ts"; +import { part1, part2 } from "./3.ts"; + +const testInput = `00100 +11110 +10110 +10111 +10101 +01111 +00111 +11100 +10000 +11001 +00010 +01010`.trim().split("\n").map((s) => s.trim()); + +Deno.test("day 3 part 1", async () => { + assertEquals(await part1(testInput), 198); +}); + +Deno.test("day 3 part 2", async () => { + assertEquals(await part2(testInput), 230); +}); diff --git a/2021/3.ts b/2021/3.ts new file mode 100644 index 0000000..2e7551c --- /dev/null +++ b/2021/3.ts @@ -0,0 +1,32 @@ +import { collectArray, inputLines, measureDuration } from "./common.ts"; +const input = await collectArray(await inputLines("3")); + +type SubmarineCommand = ["forward", number] | ["up", number] | ["down", number]; + +const ASCII_ZERO = "0".charCodeAt(0); +export function part1(input: string[]): number { + const width = input[0].length; + const counter = Array.from(Array(width), (_) => [0, 0]); + for (const l of input) { + for (let i = 0; i < width; i++) { + const val = l.charCodeAt(i) - ASCII_ZERO; + counter[i][val]++; + } + } + let ones = 0; + for (let i = 0; i < width; i++) { + if (counter[i][1] >= counter[i][0]) ones++; + ones = ones << 1; + } + ones = ones >> 1; + const zeroes = ones ^ (Math.pow(2, width) - 1); // xor with a mask the same size as the width + return ones * zeroes; +} + +await measureDuration(() => console.log("Part 1", part1(input))); + +export function part2(input: string[]): number { + return 0; +} + +await measureDuration(() => console.log("Part 2", part2(input)));