[TASK] Solved Day 3

This commit is contained in:
2021-12-04 10:29:32 +01:00
parent 32f00ea017
commit 039c36f09a
5 changed files with 1102 additions and 0 deletions

62
functions/src/day3.ts Normal file
View File

@@ -0,0 +1,62 @@
import Utils from "./utils";
class Day3 {
public static part1(input: string[]): number {
let sums = Utils.zeroes(input[0].length);
for (let value of input) {
for (let i = 0; i < value.length; i++) {
if (value[i] === "1") {
sums[i] += 1;
}
}
}
const gamma = parseInt(sums.map(s => s > input.length / 2 ? "1" : "0").join(""), 2);
const epsilon = parseInt(sums.map(s => s <= input.length / 2 ? "1" : "0").join(""), 2);
return gamma * epsilon;
}
public static part2(input: string[]): number {
return this.findLifeSupportRating(input, "oxygen") * this.findLifeSupportRating(input, "CO2");
}
static findLifeSupportRating(input: string[], type: "oxygen" | "CO2"): number {
const bits = input[0].length;
let indexesLeft = input.map((v, i) => i);
for (let bit = 0; bit < bits; bit++) {
const onesIdxs = indexesLeft.filter(j => input[j][bit] === "1")
const ones = onesIdxs.length;
if (ones >= indexesLeft.length / 2) {
// 1 is the most common, or they are equally common
if (type === "oxygen") {
indexesLeft = onesIdxs;
} else {
indexesLeft = indexesLeft.filter(j => input[j][bit] === "0")
}
} else {
// 0 is the most common
if (type === "oxygen") {
indexesLeft = indexesLeft.filter(j => input[j][bit] === "0")
} else {
indexesLeft = onesIdxs;
}
}
if (indexesLeft.length === 1) {
return parseInt(input[indexesLeft[0]], 2);
}
}
throw Error("More than one number left: " + JSON.stringify(indexesLeft));
}
}
export default Day3;

View File

@@ -3,6 +3,7 @@ import Utils from "./utils";
import Day1 from "./day1";
import {Response} from "firebase-functions";
import Day2 from "./day2";
import Day3 from "./day3";
// // Start writing Firebase Functions
@@ -35,6 +36,14 @@ export const day = {
sendResponse(response, part1, part2);
}),
3: functions.region("europe-west1").https.onRequest((request, response) => {
const input = Utils.parseInput(request);
const part1 = Day3.part1(input);
const part2 = Day3.part2(input);
sendResponse(response, part1, part2);
}),
}
function sendResponse(response: Response, part1: string | number, part2: string | number) {

View File

@@ -16,6 +16,15 @@ class Utils {
static sum(values: number[]): number {
return values.reduce((a, b) => a + b, 0);
}
static zeroes(length: number): number[] {
let res = [];
for (let i = 0; i < length; i++) {
res.push(0);
}
return res;
}
}
export default Utils;

17
input/day/3-example.http Normal file
View File

@@ -0,0 +1,17 @@
POST http://localhost:5001/advent-of-code-2021-911a8/europe-west1/day-3
Content-Type: text/plain
00100
11110
10110
10111
10101
01111
00111
11100
10000
11001
00010
01010
###

1005
input/day/3.http Normal file

File diff suppressed because it is too large Load Diff