xxxxxxxxxx
80
// My previous submission seemed to consistently produce values
// slightly below PI. I have the theory that there is a bias
// towards 45 and 135 degree angles because of the diagonals.
// Now I filter out all the initial, unscaled points that are
// not inside the circle around the center. I'm still not using
// PI in the source. The results now seem more reasonable.
// Somehow I have a feeling that Buffon's algorithm only works
// if you have a room big enough that no toothpick ever hits the
// wall. Maybe an idea for a future coding challenge? Use a physics
// engine to simulate toothpicks in a room with walls.
// I also added some other optimizations.
let t = 20;
let l = 15;
let speeed = 10000;
let crossesCount, total;
let pieP;
let syze = 400;
let radius;
function setup() {
createCanvas(syze, syze);
background(0);
stroke(255);
for (let x = 0; x <= width; x += t) {
line(x, 0, x, height);
}
radius = syze / 2;
radiusSquared = radius * radius;
crossesCount = 0;
total = 0;
pieDiv = createDiv("0.0");
pieDiv.style("background-color", "#000");
pieDiv.style("color", "#FF0");
}
function circlePoint() {
let x, y, dx, dy;
do {
x = random(syze);
y = random(syze);
dx = x - radius;
dy = y - radius;
} while (dx * dx + dy * dy > radiusSquared);
return [x, y];
}
function draw() {
for (let n = 0; n < speeed; ++n) {
let x0, x1, y0, y1;
[x0, y0] = circlePoint();
[x1, y1] = circlePoint();
xc = (x0 + x1) / 2;
yc = (y0 + y1) / 2;
let dst = dist(x0, y0, x1, y1);
let scl = l / dst;
let nx0 = xc + (x0 - xc) * scl;
let ny0 = yc + (y0 - yc) * scl;
let nx1 = xc + (x1 - xc) * scl;
let ny1 = yc + (y1 - yc) * scl;
let col0 = floor(nx0 / t);
let col1 = floor(nx1 / t);
if (col0 != col1) {
++crossesCount;
stroke(0,255,0);
} else {
stroke(255,0,0);
}
line (nx0, ny0, nx1, ny1);
}
total += speeed;
let prob = crossesCount / total;
let pie = 2 * l / (prob * t);
pieDiv.html(pie);
}