Skip to content

Instantly share code, notes, and snippets.

@kelsny
Created February 20, 2023 01:32
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kelsny/0c625c8b6b51aedbc213f5fb5bd45944 to your computer and use it in GitHub Desktop.
Save kelsny/0c625c8b6b51aedbc213f5fb5bd45944 to your computer and use it in GitHub Desktop.
// 7 points lay equally distanced on a circle. 3 points are chosen at random. What’s the probability that the triangle formed by the 3 points is acute?
const points: [x: number, y: number][] = [];
for (let i = 0; i < 7; i++) {
const angle = Math.PI * 2 * (i / 7);
points.push([Math.cos(angle), Math.sin(angle)]);
}
const combos = nck(7, 3);
const triangles = combos.map((indices) => indices.map((index) => points[index - 1]));
let count = 0;
for (const [a, b, c] of triangles) {
const sides = [
Math.hypot(a[0] - b[0], a[1] - b[1]),
Math.hypot(b[0] - c[0], b[1] - c[1]),
Math.hypot(c[0] - a[0], c[1] - a[1]),
];
const [short1, short2, long] = sides.sort((a, b) => a - b);
if (short1 ** 2 + short2 ** 2 > long ** 2) count++;
}
// ANSWER: 2 / 5 or 0.4
console.log(count / triangles.length);
function nck(n: number, k: number) {
const result: number[][] = [];
const combos: number[] = [];
const recurse = (start: number) => {
if (combos.length + (n - start + 1) < k) {
return;
}
recurse(start + 1);
combos.push(start);
if (combos.length === k) {
result.push(combos.slice());
} else if (combos.length + (n - start + 2) >= k) {
recurse(start + 1);
}
combos.pop();
};
recurse(1);
return result;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment