Created
February 2, 2020 06:24
-
-
Save acagastya/87f310733688a877dbe4ff9a8753b182 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class Point { | |
constructor(x = 0, y = 0) { | |
this.x = x; | |
this.y = y; | |
} | |
set coords({ x = 0, y = 0 }) { | |
if (!Number.isNaN(x)) this.x = x; | |
if (!Number.isNaN(y)) this.y = y; | |
} | |
get coords() { | |
const { x, y } = this; | |
return { x, y }; | |
} | |
} | |
(function crease() { | |
const LOOPS = 10 ** 9; | |
let len = 0; | |
const { sqrt: s, random: r } = Math; | |
for (let i = 0; i < LOOPS; i++) { | |
// 1. Choose a random point | |
const p = new Point(r(), r()); | |
// 2. Find slope of crease | |
const slope = p.y / p.x; | |
const m = -1 / slope; | |
// 3. Find c of crease | |
const mp = new Point(p.x / 2, p.y / 2); | |
const c = mp.y - m * mp.x; | |
// 4. Find intercept coordinates on left/top edge | |
const yInt = new Point(); | |
if (c >= 0 && c <= 1) yInt.coords = { y: c }; | |
else yInt.coords = { x: (1 - c) / m, y: 1 }; | |
// 5. Find intercept coordinates on right/bottom edge | |
const xInt = new Point(); | |
if (-c / m >= 0 && -c / m <= 1) xInt.coords = { x: -c / m }; | |
else xInt.coords = { x: 1, y: m + c }; | |
// 6. Calculate distance between the two coordinates | |
const dist = s( | |
(yInt.coords.x - xInt.coords.x) ** 2 + | |
(yInt.coords.y - xInt.coords.y) ** 2 | |
); | |
// 7. Add to the length | |
len += dist; | |
} | |
// 8. Calculate average length | |
const avgLen = len / LOOPS; | |
// 9. Calculate average percent as compared to max possible crease length | |
const percentMaxLen = (avgLen * 100) / s(2); | |
// 10. Print result | |
console.log(`Average length of crease is: ${avgLen}`); | |
console.log(`% max len: ${percentMaxLen}`); | |
})(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment