根据加权百分比随机排列一组 URL
我试图弄清楚如何根据百分比对 URL 数组进行洗牌,以便每个 URL 都被选择一定次数。
<?php
$urls = array(
'http://www.google.com'=>'25%',
'http://www.yahoo.com'=>'25%',
'http://www.bing.com' =>'50%');
我考虑过使用 rand() 路线,只获取 1-100 之间的随机数,并使用一系列范围创建 switch 语句,但这似乎不够优雅和笨拙。我也不知道这样做有多可靠。我正在努力尽可能接近完美。如果我随机播放 100 次,我不确定大多数 rand() 示例是否会列出上述数组,其中 google.com 和 yahoo.com 各被选择 25 次 (+/- 2),而 bing.com 被选择 50 次。
他们是一种获得准确加权洗牌的方法吗?谢谢
I am trying to figure out how to shuffle an array of URL's based on a percentage so that each URL get's picked a certain number of times.
<?php
$urls = array(
'http://www.google.com'=>'25%',
'http://www.yahoo.com'=>'25%',
'http://www.bing.com' =>'50%');
I thought about going the rand() route and just getting a random number between 1-100 and making a switch statement with a bunch of ranges, but that seems less than elegant and clumsy. I also don't know how reliable doing this would be. I am trying to get as close to perfect as possible. If I shuffle through 100 times I am not sure most of the rand() examples would list the above array with google.com and yahoo.com getting selected 25 times each (+/- 2) and bing.com getting selected 50 times.
Is their a way to get accurate weighted shuffling? Thanks
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
你仍然想要兰特。在 100 的分布中,您不太可能获得完全均匀的 100% 分布。如果你想要这样,你需要将状态存储在数据库中,或者以某种方式静态存储到服务器本身。事实上,您要做的只是递减数组值,直到它们全部为 0,然后重新开始。
以下是在没有完美匹配分布的情况下它如何工作的表示(假设它在函数中):
You'll still want a rand. In a distribution of 100, you're not likely to get a perfectly even 100% distribution. If you want that, you'll need to store state in a DB, or somehow static to the server itself. In fact, what you would do is just decrement the array values until they're all 0, then start again.
Here is a representation of how it would work without the perfect-match distribution (assuming it is in a function):
下面的逻辑怎么样?
How about the following logic?
看起来你可以这样做:
要获取前面的值,只需调用
key
:或者,你可以迭代整个过程:数组是随机值:
It looks like you could just do:
To get the value in front, just call
key
:Or, you could just iterate through the whole thing: the array is in a randomized value:
试试这个
Try this