96 lines
2.3 KiB
TypeScript
96 lines
2.3 KiB
TypeScript
import { readLines } from "https://deno.land/std@0.177.1/io/read_lines.ts";
|
|
|
|
async function Part1() {
|
|
const file = await Deno.open("./Day3/input.txt");
|
|
const lines = readLines(file);
|
|
|
|
let line = (await lines.next()).value as string;
|
|
const bits: number[] = new Array(line.length).fill(0);
|
|
let NrOfLines = 1;
|
|
|
|
for (let i = 0; i < line.length; i++) {
|
|
if (line[i] == '1') {
|
|
bits[i]++;
|
|
}
|
|
}
|
|
|
|
for await (line of lines) {
|
|
NrOfLines++;
|
|
for (let i = 0; i < line.length; i++) {
|
|
if (line[i] == '1') {
|
|
bits[i]++;
|
|
}
|
|
}
|
|
}
|
|
|
|
let gamma = 0;
|
|
let epsilon = 0;
|
|
|
|
for (let i = bits.length - 1; i >= 0; i--) {
|
|
if (bits[i] > NrOfLines/2) {
|
|
gamma += 2**((bits.length - 1) - i);
|
|
} else {
|
|
epsilon += 2**((bits.length - 1) - i);
|
|
}
|
|
}
|
|
|
|
return gamma * epsilon;
|
|
}
|
|
|
|
async function Part2() {
|
|
const file = await Deno.open("./Day3/input.txt");
|
|
const lines = readLines(file);
|
|
|
|
let OxygenLines: string[] = [];
|
|
let CO2Lines: string[] = [];
|
|
|
|
for await (const line of lines) {
|
|
OxygenLines.push(line);
|
|
CO2Lines.push(line);
|
|
}
|
|
|
|
const ReadingLength = OxygenLines[0].length;
|
|
|
|
for (let i = 0; i < ReadingLength; i++) {
|
|
|
|
if (OxygenLines.length > 1) {
|
|
const OxyBit = mostCommonBit(OxygenLines,i);
|
|
OxygenLines = OxygenLines.filter(reading => +reading[i] == OxyBit);
|
|
}
|
|
|
|
if (CO2Lines.length > 1) {
|
|
const CO2Bit = mostCommonBit(CO2Lines,i);
|
|
CO2Lines = CO2Lines.filter(reading => +reading[i] != CO2Bit);
|
|
}
|
|
}
|
|
|
|
const OxygenReading = OxygenLines[0];
|
|
const CO2Reading = CO2Lines[0];
|
|
|
|
let OxygenLevel = 0;
|
|
let CO2Level = 0;
|
|
|
|
for (let i = ReadingLength - 1; i >= 0; i--) {
|
|
OxygenLevel += +OxygenReading[i] * 2**(ReadingLength - 1 - i);
|
|
CO2Level += +CO2Reading[i] * 2**(ReadingLength - 1 - i);
|
|
}
|
|
|
|
return OxygenLevel * CO2Level;
|
|
}
|
|
|
|
function mostCommonBit(arr: string[], index: number): 0 | 1 {
|
|
let count = 0;
|
|
for (const line of arr) {
|
|
if (line[index] == '1') {
|
|
count++;
|
|
}
|
|
}
|
|
if (count >= arr.length/2) {
|
|
return 1
|
|
}
|
|
return 0
|
|
}
|
|
|
|
console.log("Part1: " + await Part1());
|
|
|
|
console.log("Part2: " + await Part2()); |