From 164412b22e86e8cefdc20a8956271ed463094787 Mon Sep 17 00:00:00 2001 From: Dan Wysocki Date: Tue, 5 May 2015 17:37:39 -0400 Subject: [PATCH] Rewriting weighted random --- src/core/Configuration.js | 18 +----------------- src/core/Main.js | 8 ++++++-- src/core/Util.js | 18 ++++++++++++++++++ 3 files changed, 25 insertions(+), 19 deletions(-) diff --git a/src/core/Configuration.js b/src/core/Configuration.js index 159641f..62f8e4f 100644 --- a/src/core/Configuration.js +++ b/src/core/Configuration.js @@ -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; - } - } - } } diff --git a/src/core/Main.js b/src/core/Main.js index 80022d3..7e152d2 100644 --- a/src/core/Main.js +++ b/src/core/Main.js @@ -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, @@ -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, diff --git a/src/core/Util.js b/src/core/Util.js index 7707568..f57a95f 100644 --- a/src/core/Util.js +++ b/src/core/Util.js @@ -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. *