Last active
August 2, 2019 09:33
-
-
Save ktpm489/af343a6f71c22ae28193de508748adfb to your computer and use it in GitHub Desktop.
weighted-biased-random-number-generation
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
| var rand = function(min, max) { | |
| return Math.random() * (max - min) + min; | |
| }; | |
| var getRandomItem = function(list, weight) { | |
| var total_weight = weight.reduce(function (prev, cur, i, arr) { | |
| return prev + cur; | |
| }); | |
| var random_num = rand(0, total_weight); | |
| var weight_sum = 0; | |
| //console.log(random_num) | |
| for (var i = 0; i < list.length; i++) { | |
| weight_sum += weight[i]; | |
| weight_sum = +weight_sum.toFixed(2); | |
| if (random_num <= weight_sum) { | |
| return list[i]; | |
| } | |
| } | |
| // end of function | |
| }; | |
| var list = ['javascript', 'php', 'ruby', 'python','lost']; | |
| var weight = [0.15, 0.05, 0.3, 0.5, 0 ]; | |
| let arrItem = [] | |
| for (var i = 0 ; i < 100;i++) { | |
| var random_item = getRandomItem(list, weight); | |
| // console.log(random_item + ''); | |
| arrItem.push(random_item) | |
| } | |
| function searchExist(searchVal ,arr) { | |
| var count = arr.filter(function(item) { | |
| return item === searchVal | |
| }).length; | |
| console.log('searchVal:' +searchVal +'--:' count) | |
| } | |
| for (var j = 0; k < list.length; j++) { | |
| searchExist(list[j],arrItem) | |
| } | |
| console.log('1') |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment