aoc-2023/day_6/solve.ts

68 lines
1.3 KiB
TypeScript
Raw Permalink Normal View History

2024-12-09 22:41:02 +09:00
/**
* Time: 7 15 30
* Distance: 9 40 200
*/
const example = [
{
time: 7,
distance: 9
},
{
time: 15,
distance: 40
},
{
time: 30,
distance: 200
}
]
/**
* Time: 58 99 64 69
* Distance: 478 2232 1019 1071
*/
const input = [
{
time: 58,
distance: 478
},
{
time: 99,
distance: 2232
},
{
time: 64,
distance: 1019
},
{
time: 69,
distance: 1071
}
]
function caculRangeOfBeatRecord(time: number, distance: number) {
const mid = time / 2;
const dist = Math.sqrt(Math.pow(time, 2) / 4 - distance);
return {
start: mid - dist, // include
end: mid + dist, // exclude
}
}
/**
* count natrual numbers in the range. it could be real number.
* @param {number} start
* @param {number} end
* @returns natrual numbers in the range
*/
function countRange(start: number, end: number) {
return Math.ceil(end - 1) - Math.floor(start + 1) + 1
}
const res = input.map(e => {
const range = caculRangeOfBeatRecord(e.time, e.distance);
const count = countRange(range.start, range.end);
console.log(range, count)
return count;
}).reduce((a, b) => a * b, 1);
console.log(res);