Weighted

by Sam Fereday

HTML

<div id="output">
  <div id="left">A:
    <div id="aout"></div>
  </div>
  <div id="right">B:
    <div id="bout"></div>
  </div>
</div>
<button id="start">
  Start
</button>

CSS

body {
  font: 75%/1.4em arial;
}

#output {
  padding: 1em;
  color: #fff;
  background: #333;
  overflow: auto;
}

button {
  border: 0;
  margin-top: 1em;
  padding: 1em;
  background: #fff;
  color: #333;
  cursor: pointer;
  transition: all 0.2s ease;
}

button:hover {
  background: #eee;
}

#left, #right {
  width: 50%;
  float: left;
  text-align: center;
}

JavaScript

console.clear();

function getSum(total, num) {

  return total + num;

}

function rand(min, max) {

  return Math.random() * (max - min) + min;

}

function weighted(weights) {

  let totalWeight = weights.reduce(getSum),
    randomNumber = rand(0, totalWeight),
    weight_sum = 0,
    i = 0,
    len = weights.length;

  for (i; i < len; i++) {

    weight_sum += weights[i];

    if (randomNumber <= weight_sum)
      return i;

  }

}

document.getElementById("start").addEventListener('click', function() {
  var index = weighted([0.2, 0.8]);
  console.log(index);
  if(index < 1) {
    document.getElementById("aout").innerHTML += index;
  } else {
    document.getElementById("bout").innerHTML += index;
  }
});