aoc-2023/day_6/solve_2.ts

48 lines
1.1 KiB
TypeScript
Raw Normal View History

2024-12-09 22:41:02 +09:00
/**
* Time: 7 15 30
* Distance: 9 40 200
*/
const example = [
{
time: 71530,
distance: 940200,
}
]
/**
* Time: 58 99 64 69
* Distance: 478 2232 1019 1071
*/
const input = [
{
time: 58996469,
distance: 478223210191071,
},
]
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);