Last active
August 29, 2015 14:26
-
-
Save SirGordon/b4cdabcaa95251885f3f to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| public static function generateRandomResultBasedOnWeights(weights:Array):int { | |
| weights.sort(Array.DESCENDING); | |
| var sum:Number = sumArrayElements(weights); | |
| var r:Number = Math.random() * sum; | |
| var result:int = -1; | |
| for (var i:uint = 0; i < weights.length; i++) { | |
| var item:int = weights[i]; | |
| if (r < item) | |
| return result; | |
| r -= item; | |
| } | |
| return result; | |
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| function generateRandomResultBasedOnWeights(weights) { | |
| //weights.sort(sortFunction); | |
| var sum = sumArrayElements(weights); | |
| console.log("sum: " + sum); | |
| var r = Math.random() * sum; | |
| var result = {value: "nothing"}; | |
| for (var i = 0; i < weights.length; i++) { | |
| var item = weights[i]; | |
| if (r < item.weight) | |
| return item; | |
| r -= item.weight; | |
| } | |
| return result; | |
| } | |
| function sumArrayElements(array){ | |
| var result = 0; | |
| for(var i = 0; i<array.length; i++){ | |
| result += array[i].weight; | |
| } | |
| return result; | |
| } | |
| function sortFunction(a, b) { | |
| return b.weight - a.weight; | |
| } | |
| function main(){ | |
| var arr = [ | |
| {value:"gold", weight:70}, | |
| {value:"potion", weight:20}, | |
| {value:"shit", weight:10} | |
| ]; | |
| arr = arr.sort(sortFunction); | |
| var results = { | |
| gold: 0, | |
| potion: 0, | |
| shit: 0, | |
| nothing: 0 | |
| }; | |
| for(var i=0; i<10000; i++){ | |
| var result = generateRandomResultBasedOnWeights(arr); | |
| results[result.value]++; | |
| } | |
| alert("gold " + results.gold + "\npotion " + results.potion + "\nshit " + results.shit + "\nnothing " + results.nothing); | |
| //output: gold ~7000, potion ~2000, shit ~1000 | |
| } | |
| main(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment