updating p5js examples
lingtalfi opened this issue · 0 comments
lingtalfi commented
Hi, I'm following the youtube playlist on nature of code, and I didn't found the corresponding p5.js code for the Custom Distribution video (https://www.youtube.com/watch?v=DfziDXHYoik).
So here is the code I created, based on the processing equivalent:
// An array to keep track of how often random numbers are picked
let randomCounts = [];
function setup() {
background(200);
createCanvas(800, 200);
for (var i = 1; i <= 20; i++) {
randomCounts.push(0);
}
}
function draw() {
background(255);
// Pick a random number and increase the count
var index = int(acceptreject() * randomCounts.length);
randomCounts[index]++;
// Draw a rectangle to graph results
stroke(0);
strokeWeight(2);
fill(127);
var w = width / randomCounts.length;
for (var x = 0; x < randomCounts.length; x++) {
rect(x * w, height - randomCounts[x], w - 1, randomCounts[x]);
}
}
// An algorithm for picking a random number based on monte carlo method
// Here probability is determined by formula y = x
function acceptreject() {
// Have we found one yet
var foundone = false;
var hack = 0; // let's count just so we don't get stuck in an infinite loop by accident
while (!foundone && hack < 10000) {
// Pick two random numbers
var r1 = float(random(1));
var r2 = float(random(1));
var y = r1 * r1; // y = x*x (change for different results)
// If r2 is valid, we'll use this one
if (r2 < y) {
foundone = true;
return r1;
}
hack++;
}
// Hack in case we run into a problem (need to improve this)
return 0;
}
Hopefully you can update your repository and add this code example too.
Cheers.