TE
科技回声
首页24小时热榜最新最佳问答展示工作
GitHubTwitter
首页

科技回声

基于 Next.js 构建的科技新闻平台,提供全球科技新闻和讨论内容。

GitHubTwitter

首页

首页最新最佳问答展示工作

资源链接

HackerNews API原版 HackerNewsNext.js

© 2025 科技回声. 版权所有。

Weighted/Biased Random Number Generation with JavaScript based on Probability

19 点作者 luzon19大约 12 年前

4 条评论

mrcactu5大约 12 年前
You can take relative weights (a,b,c) and take the partial sums:<p>(0,a,a+b,a+b+c)<p>random() gives values in [0,1], so divide your numbers by a + b + c.<p>Generating random structures is the tip of a very big iceberg.
jere大约 12 年前
I came up with something pretty similar while generating items. However, the following code gets pretty hard to read with lots of items because the values don't line up. And while balancing, you will want to be able to read and modify it <i>very easily</i>:<p>&#62;var list = ['javascript', 'php', 'ruby', 'python']; var weight = [0.5, 0.2, 0.2, 0.1];<p>You could instead put each into an object: { language: 'javascript', weight: 0.5 }<p>My code (in the itemRoll function) demonstrates this, but it is a little bit more rolled out because I was instantiating objects: <a href="http://humbit.com/rogue/afsahr-v1.2/js/inventory.js" rel="nofollow">http://humbit.com/rogue/afsahr-v1.2/js/inventory.js</a>
dllu大约 12 年前
For method 2, if you precompute the cumulative distribution function, you can do a binary search which is only O(log N) instead of O(N).
BadCRC大约 12 年前
why not have a dynamic multiplier based on the weights? rather than just 100x