summaryrefslogtreecommitdiff
path: root/day-6/script.ts
blob: 7cd15afb54bd9096422bdaaecaff2e50a3b813e0 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
import fs from "fs";

const input = fs.readFileSync("./input.txt").toString();

const [time, distance] = input
  .split("\n")
  .slice(0, 2)
  .map((s) => s.match(/\d+/g)?.join("") || "")
  .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 = numberOfWaysToWin(time, distance);

console.log(result);