Skip to content

Commit

Permalink
Rewriting weighted random
Browse files Browse the repository at this point in the history
  • Loading branch information
dwysocki committed May 5, 2015
1 parent fa916cd commit 164412b
Show file tree
Hide file tree
Showing 3 changed files with 25 additions and 19 deletions.
18 changes: 1 addition & 17 deletions src/core/Configuration.js
Original file line number Diff line number Diff line change
Expand Up @@ -9,24 +9,8 @@ function Configuration(width, height, colors, magnitudes, specials, types, turns

this.getRandomShell = function() {
return new Shell(Util.selectRandom(colors),
weightedMagnitude(),
Util.selectWeightedRandom(magnitudes),
Util.selectRandom(types),
Util.selectRandom(specials));
}
function weightedMagnitude(){
var weights = new Map([]);
weights.set(1, .40);
weights.set(2, .30);
weights.set(3, .15);
weights.set(4, .10);
weights.set(5, .05);
var p = 1 - Math.random();
for(var i = 1; i <= 5 ; i++){
var current = weights.get(i)
p = p - current;
if(p <= 0){
return i;
}
}
}
}
8 changes: 6 additions & 2 deletions src/core/Main.js
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@ var app = Cut(function(root, container) {

setViewBox(width, height, 40, root);

var magnitudes = [0];
var magnitudes = [[0, 1.0]];
var specials = [null];
var types = [Shariki.NORMALSHELL];
var config = new Configuration(width, height,
Expand All @@ -38,7 +38,11 @@ var app = Cut(function(root, container) {

setViewBox(width, height, 40, root);

var magnitudes = [1, 2, 3, 4, 5];
var magnitudes = [[1, 0.40],
[2, 0.30],
[3, 0.15],
[4, 0.10],
[5, 0.05]];
var specials = [null];
var types = [Bombi.NORMALSHELL];
var config = new Configuration(width, height,
Expand Down
18 changes: 18 additions & 0 deletions src/core/Util.js
Original file line number Diff line number Diff line change
Expand Up @@ -58,6 +58,24 @@ Util.selectRandom = function(arr) {
return arr[Util.randomInt(arr.length)];
};

/**
* Returns a random key from an array of key-value pairs, where the values are
* the weights. Assumes that values are stochastic (sum to 1.0).
*
* @param map {Object[][]}
*
* @return {Object}
*/
Util.selectWeightedRandom = function(arr) {
var p = 1 - Math.random();
for(var i = 0; i < arr.length; ++i) {
p -= arr[i][1];
if(p <= 0) {
return arr[i][0];
}
}
}

/**
* Returns a coordinate object.
*
Expand Down

0 comments on commit 164412b

Please sign in to comment.