adventofcode2023/day6/day6-ts.ts

59 lines
1.3 KiB
TypeScript
Raw Normal View History

2023-12-07 08:37:58 +01:00
type Race = {
time: number;
distance: number;
};
const races: Race[] = [];
2023-12-07 08:43:41 +01:00
const timeFrom = new Date().getTime();
2023-12-07 08:41:15 +01:00
// const input = `Time: 47 70 75 66
// Distance: 282 1079 1147 1062`.split("\n");
const input = `Time: 47707566
Distance: 282107911471062`.split("\n");
2023-12-07 08:37:58 +01:00
// parse input
const [t, ...rtimes] = input[0].split(" ");
const times = rtimes.filter((o) => o !== "").map((o) => Number(o));
const [d, ...rdist] = input[1].split(" ");
const dist = rdist.filter((o) => o !== "").map((o) => Number(o));
for (let i = 0; i < times.length; i++) {
races.push({ time: times[i], distance: dist[i] });
}
console.log(races);
function getSpeed(race: Race, holdTime: number): number {
return (race.time - holdTime) * holdTime;
}
const counts: number[] = [];
for (const race of races) {
let from = 1;
let to = 1;
for (let i = 0; i < race.time; i++) {
if (getSpeed(race, i) > race.distance) {
from = i;
break;
}
}
for (let i = race.time; i >= 0; i--) {
if (getSpeed(race, i) > race.distance) {
to = i;
break;
}
}
counts.push(to - from + 1);
}
2023-12-07 08:41:15 +01:00
let mul = 1;
2023-12-07 08:37:58 +01:00
for (const count of counts) {
mul *= count;
}
console.log(mul);
2023-12-07 08:43:41 +01:00
const timeTotal = new Date().getTime() - timeFrom;
console.log(`Time took: ${timeTotal}ms`);