Day 3 part 1 done

This commit is contained in:
Daniel Flanagan 2021-12-03 09:36:46 -06:00
parent 5302424d01
commit 1ef1c05668
Signed by: lytedev
GPG key ID: 5B2020A0F9921EF4
2 changed files with 55 additions and 0 deletions

23
2021/3.test.ts Normal file
View file

@ -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);
});

32
2021/3.ts Normal file
View file

@ -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)));