php百分比机会 [英] php percentage chance

查看:49
本文介绍了php百分比机会的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这实际上更多是一个方法问题,但我是在 php 中提出的.

This is really more a question of approach, but I'm presenting it in php.

假设我们有一个包含四个百分比的列表,一个给定事件将在迭代中发生.

Suppose we had a list of four percentages that a give event will occur on iteration.

array=('walk the dog'=>.25,'read the paper'=>.25,'drink coffee'=>.0,'listen to music'=>.50)

(键只是测试 - 在实践中,这将用于策略模式,使用 call_user_func() 将不同的方法应用于偶然的对象)

(Keys are just tests - in practice this is going to be used in a strategy pattern that applies different methods to an object off chance using call_user_func())

在一个循环中,通过随机调整选择考虑到它们各自的权重来选择这些事件之一的最佳方法是什么(即,对于这种特定配置,将听到很多音乐而不是喝了很多咖啡)

In a loop, what would be the best way to choose one of these events by random-adjusted selection taking their respective weights into account (IE, for this particular configuration, there will be a lot of music listened to and not a lot of coffee drank)

目前我有类似的东西:

for($i=1;$i<=3;$i++){
  $rand = 1/rand(1,10);
  //choose from the list
}

但这需要将百分比映射到值范围(50-100% 成为听音乐,0-25% 遛狗和 25-50 阅读论文),因为该迭代的值"计算为0 到 1 之间的浮点数.这种改变了需要记录百分比的方式.

But this would require mapping the percentages to value ranges (50-100% become listening to music, 0-25% walking the dog and 25-50 reading the paper) because the 'value' for that iteration is calculated as a floating point number between 0 and 1. This kind of changes the way the percentages need to be recorded.

是否有任何一种方法可以保留值的身份作为它们应该被选择的真实概率而不是范围?这肯定会使代码更具可配置性,因为我必须使这些值可调整.如果我太含糊,请告诉我.

Is there any kind of approach that would preserve the identity of the values as the real probability they should be chosen rather than ranges? It would definitely make the code more configurable since I have to make these values adjustable. Please let me know if I've been too vague.

推荐答案

我会这样做:

$arr = array (
    'walk the dog'    =>  array('min' =>  0, 'max' =>  25),
    'read the paper'  =>  array('min' => 25, 'max' =>  50),
    'drink coffee'    =>  array('min' =>  0, 'max' =>   0),
    'listen to music' =>  array('min' => 50, 'max' => 100),
);

$rnd = rand(1,100);
foreach($arr as $k =>$v) {
    if ($rnd > $v['min'] && $rnd <= $v['max']) {
        echo $k,"\n";
    }
}

这篇关于php百分比机会的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆