[TASK] Solved Day 7
This commit is contained in:
45
functions/src/day7.ts
Normal file
45
functions/src/day7.ts
Normal file
@@ -0,0 +1,45 @@
|
||||
import Day from "./day";
|
||||
import Utils from "./utils";
|
||||
|
||||
class Day7 implements Day {
|
||||
|
||||
part1(input: string[]): number | string {
|
||||
|
||||
const initialPositions = input[0].split(",").map(s => parseInt(s));
|
||||
initialPositions.sort((a, b) => a - b);
|
||||
|
||||
// The optimal position is just the median:
|
||||
const pos = initialPositions[Math.floor(initialPositions.length / 2)];
|
||||
|
||||
// So we calculate the fuel usage in that position
|
||||
return Utils.sum(initialPositions.map(p => Math.abs(pos - p)));
|
||||
}
|
||||
|
||||
|
||||
part2(input: string[]): number | string {
|
||||
|
||||
const initialPositions = input[0].split(",").map(s => parseInt(s));
|
||||
const min = Math.min(...initialPositions);
|
||||
const max = Math.max(...initialPositions);
|
||||
|
||||
const fuelUsage = Array(max + 1);
|
||||
let lastFuel = 0;
|
||||
for (let i = 0; i < fuelUsage.length; i++) {
|
||||
fuelUsage[i] = lastFuel + i;
|
||||
lastFuel = fuelUsage[i];
|
||||
}
|
||||
|
||||
let bestFoundFuelCost = Number.MAX_SAFE_INTEGER;
|
||||
for (let pos = min; pos < max; pos++) {
|
||||
|
||||
const fuelCost = Utils.sum(initialPositions.map(p => fuelUsage[Math.abs(pos - p)]));
|
||||
if (fuelCost < bestFoundFuelCost) {
|
||||
bestFoundFuelCost = fuelCost;
|
||||
}
|
||||
}
|
||||
|
||||
return bestFoundFuelCost;
|
||||
}
|
||||
}
|
||||
|
||||
export default Day7;
|
||||
@@ -8,6 +8,7 @@ import Day3 from "./day3";
|
||||
import Day4 from "./day4";
|
||||
import Day5 from "./day5";
|
||||
import Day6 from "./day6";
|
||||
import Day7 from "./day7";
|
||||
|
||||
|
||||
// // Start writing Firebase Functions
|
||||
@@ -30,6 +31,7 @@ export const day = {
|
||||
4: functions.region("europe-west1").https.onRequest((request, response) => { processDay(new Day4(), request, response) }),
|
||||
5: functions.region("europe-west1").https.onRequest((request, response) => { processDay(new Day5(), request, response) }),
|
||||
6: functions.region("europe-west1").https.onRequest((request, response) => { processDay(new Day6(), request, response) }),
|
||||
7: functions.region("europe-west1").https.onRequest((request, response) => { processDay(new Day7(), request, response) }),
|
||||
|
||||
}
|
||||
|
||||
|
||||
Reference in New Issue
Block a user