Skip to content

Instantly share code, notes, and snippets.

@gubatron
Last active February 22, 2023 13:31
Show Gist options
  • Save gubatron/c34ade4cac34c02355da0a66db840cbc to your computer and use it in GitHub Desktop.
Save gubatron/c34ade4cac34c02355da0a66db840cbc to your computer and use it in GitHub Desktop.
simulation of balls falling into normal distribution to teach javascript
function rand(max) {
return parseInt(Math.random() * max);
}
function f(h, i) {
if (rand(1000) < 500) {
return i
}
return i + 1
}
function zerofill (list) {
i = 0
n = list.length
while (i < n) {
list[i++] = 0
}
}
function simulation(balls, depth) {
result_list = Array(depth)
zerofill(result_list)
b = 0
while (b < balls) {
h=0
i=0
while (h < depth) {
i = f(h, i)
h=1+h
}
result_list[i] = result_list[i] + 1
b++
}
logArray(result_list)
}
function log(s) {
console.log(s)
}
function logArray(l) {
i = -1
while (++i < l.length) {
log("i = "+ i + " = " + l[i])
}
}
function testZeroFill() {
l = Array(100)
x = zerofill(l)
log("x is ... " + x)
}
//testZeroFill()
balls = 9000000
depth = 20
simulation(balls, depth)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment