0

我需要生成n ( $size_of_list) 个名称的列表...可能的成员在数组 ( $names_list) 中给出,它给出了名称和该名称出现的机会。所以它是一个包含 40 个字符串和整数数组的数组:

$names_list = array (
                     0 => array ('name' => "Mike", 'frequency' => 8),
                     1 => array ('name' => "Jane", 'frequency' => 7),
                     2 => array ('name' => "Leopold", 'frequency' => 1),
                     3 => array ('name' => "George", 'frequency' => 5),
...
                     39 => array ('name' => "Mark", 'frequency' => 6)
                    )

$names_list[0] = array('name' => "Mike", 'frequency' => 8)意味着 $name="Mike" 的 $frequency(或机会)为 8,而 "Leopold" 的机会值为 1 - 出现的机会很小...

4

2 回答 2

1

指定 $size_of_list 并在最后签出 $result。这取决于重量使用随机。

$result = array();

$total = 0;
foreach ($names_list as $row) {
    $total += $row['frequency'];
}

$max = mt_getrandmax();
$pre_sum = $total / $max;

for ($i = 0; $i < $size_of_list; ++$i) {

    $sum = $pre_sum * mt_rand(0, $max); // $sum = $total * (mt_rand(0, $max)/$max);

    foreach ($names_list as $row) {
        if (($sum -= $row['frequency']) < 0) {
            $result[] = $row['name'];
            break;
        }
    }
}

var_dump($result);
于 2013-07-08T14:23:03.967 回答
0

我的想法是用新值扩展数组,该值'rnd'表示$frequency和先前元素的总和rnd(其中第一个元素“rnd”是第一个元素的“频率”)

$names_list[0]['rnd'] = $names_list[0]['frequency'];
for ($i=1; $i<count($names_list); $i++)
    $names_list[$i]['rnd'] = $names_list[$i]['frequency'] + $names_list [$i-1]['rnd'];  

扩展数组如下所示:

$names_list = array (
                     0 => array ('name' => "Mike", 'frequency' => 8, 'rnd' => 8),
                     1 => array ('name' => "Jane", 'frequency' => 7, 'rnd' => 15),
                     2 => array ('name' => "Leopold", 'frequency' => 1, 'rnd' => 16),
                     3 => array ('name' => "George", 'frequency' => 5, 'rnd' => 21),
//... other elements
                     39 => array ('name' => "Mark", 'frequency' => 8, 'rnd' => $sum_of_all_frequencies)
                    )

然后将 $rand_max 设置为最后一个元素的值'rnd',然后通过比较$random和所有'rnd'值来创建结局列表......

$rand_max = $names_list[count($names_list)-1]['rnd'];

for ($i=1; $i<$size_of_list; $i++)
{
    $random = rand (1, $rand_max);
    $result = $names_list[0]['name'];
    foreach ($names_list as $key => $val)
        if ( ($random) > ($val['rnd']) )
            $result = $names_list[$key+1]['name'];

    $list[$i] = $result;
}

这个解决方案有效,但我认为有更好(更智能)的方法......
我将不胜感激任何帮助/建议......

于 2013-07-08T14:11:23.393 回答