Last active
October 13, 2020 20:07
-
-
Save TheTexasDev/f169797b671b74f3fa6c3ab6abe791cc to your computer and use it in GitHub Desktop.
Has a Pseudo Random number generator, input keys with numerical values as an object into the function and get a uneven random output
This file contains 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 RandomGen(min,max){ // random number | |
return Math.round(Math.random()*max-min)+min; | |
} | |
function PRandomGen(obj){ // pseudo random number | |
// {"thing": 2, "otherthing": 6} // 'otherthing' will be 3x more likely to be returned since 6 is three times 2 | |
var toReturn, sortable = [], total = 0; | |
for(var x in obj){ // loops through all values in the object | |
sortable.push([x, obj[x]]); // adds them to the array like: [["thing", 1], ["otherthing", 2]] | |
total += obj[x]; // adds the values of the keys to the total, which will allow for a maximum random number | |
} | |
sortable.sort(function(a, b) { // sort the array | |
return a[1] - b[1]; // sorts so the smallest are first | |
}); | |
var generation = Math.round(Math.random()*total); // generate a number with the maximum we got earlier | |
var decide = Math.floor((generation/total)*sortable.length); // this is the actual generation that makes higher numbers more common | |
if(decide > sortable.length-1) decide -= 1; // if its larger than the array just make it go down one | |
toReturn = sortable[decide][0]; // return the key instead of the value | |
return toReturn; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment