diff options
author | eug-vs <eugene@eug-vs.xyz> | 2023-12-06 13:26:06 +0300 |
---|---|---|
committer | eug-vs <eugene@eug-vs.xyz> | 2023-12-06 13:26:06 +0300 |
commit | c49ccc971c3a7b05dc08386833bfa4935456ff15 (patch) | |
tree | 7e59b55b5c0a250459cc2fe98d0819a4f38106cf | |
parent | 50848c9299ededef12261011eaca60037aabcb42 (diff) | |
download | aoc-2023-c49ccc971c3a7b05dc08386833bfa4935456ff15.tar.gz |
feat(day-6): add part 1 solution
-rw-r--r-- | day-6/input.txt | 2 | ||||
-rw-r--r-- | day-6/script.ts | 29 |
2 files changed, 31 insertions, 0 deletions
diff --git a/day-6/input.txt b/day-6/input.txt new file mode 100644 index 0000000..e5c8984 --- /dev/null +++ b/day-6/input.txt @@ -0,0 +1,2 @@ +Time: 59 70 78 78 +Distance: 430 1218 1213 1276 diff --git a/day-6/script.ts b/day-6/script.ts new file mode 100644 index 0000000..951e056 --- /dev/null +++ b/day-6/script.ts @@ -0,0 +1,29 @@ +import fs from "fs"; + +const input = fs.readFileSync("./input.txt").toString(); + +const [times, distances] = input + .split("\n") + .slice(0, 2) + .map((s) => s.match(/\d+/g)?.map(Number) || []); + +function numberOfWaysToWin(time: number, record: number) { + // Solution to quadratic: + // x(time-x) > record + // on the domain [0, time] + const sqrt = Math.sqrt(time * time - 4 * record); + const [min, max] = [-1, +1].map((sign) => 0.5 * (time + sqrt * sign)); + + const wholeMin = Math.floor(min) + 1; + const wholeMax = Math.ceil(max); + return wholeMax - wholeMin; +} + +const result = times + .map((time, index) => { + const distance = distances[index]; + return numberOfWaysToWin(time, distance); + }) + .reduce((acc, v) => acc * v, 1); + +console.log(result); |