JSFiddle - React, Tailwind, and code Playground
HTML
<input type="button" value=" Stop " /><br/>
CSS
div.bar {
float:left;
width:50px;
background-color: green;
margin:1px;
color:white; }
br {
clear: both; }
JavaScript
(function() {
var min = -5, max = 5, num, i,
$div = $("<div/>").attr("class","bar"),
$unit = $("<div/>").attr("class","unit"),
arr = [], count = 0, height = 1000, pos, neg, status = 0;
// Returns a random integer between min and max
// Using Math.round() will give you a non-uniform distribution!
function ran(min, max)
{
return Math.floor(Math.random() * (max - min + 1)) + min;
}
function moveIt()
{
num = ran(min, max);
arr[num] += 1; ++count;
$("#b" + num).css("height", height * arr[num]/count);
$("#b" + num).find("span").html(arr[num]);
pos = 0; neg = 0;
for (i = min; i < 0; ++i)
{
neg += arr[i] * i;
}
for (i = max; i > 0; --i)
{
pos += arr[i] * i;
}
$("#display").html("Negatives: " + neg + "<br/>Positives: " + pos +
"<br/>Sum: " + (neg + pos));
if (++status % 1000 === 0)
$("#status").append((neg + pos) + "<br/>");
}
$(function() { ;
for (i = min; i <= max; ++i)
{
$div.clone().attr("id","b" + i).html(i + "<br/><span></span>").appendTo("body");
arr[i]=0;
}
$("body").append('<br/><br/><div id="display"></div><div id="status">Sums:<br/></div>')
timer = setInterval(moveIt, 1);
$("input").toggle(function(){
clearInterval(timer);
this.value = " Go ";
},function() {
timer = setInterval(moveIt, 1);
this.value = " Stop ";
});
});
}());