【问题标题】:Rate of occurance of an event [duplicate]事件的发生率[重复]
【发布时间】:2014-05-30 10:34:37
【问题描述】:

我在这样的数组中有 12 个项目:

$item[1] = array('pseudo' => 'Item1', 'name' => 'apple', 'rarity' => '1', 'id' => '1' );
$item[2] = array('pseudo' => 'Item2', 'name' => 'banana', 'rarity' => '30', 'id' => '8' );
$item[3] = array('pseudo' => 'Item3', 'name' => 'cherry', 'rarity' => '23', 'id' => '12' );
$item[4] = array('pseudo' => 'Item4', 'name' => 'pear', 'rarity' => '27', 'id' => '18' );
$item[5] = array('pseudo' => 'Item5', 'name' => 'watermelon', 'rarity' => '70', 'id' => '14' );
$item[6] = array('pseudo' => 'Item6', 'name' => 'orange', 'rarity' => '100', 'id' => '17' );

我需要的是随机打印 6 个项目中的 1 个,但会受到其稀有度的影响,因此它越稀有,它发生的次数就越少,稀有度为 1-100。如何使用 php 完成此操作?

【问题讨论】:

  • 那么它不再是随机的了,是吗?
  • Amal 你的评论让我发笑,谢谢^^

标签: php


【解决方案1】:

您可以根据项目的稀有程度将每个项目键的 x 个副本添加到数组中。例如:

$pool = array();

foreach ($items as $key => $value) {

    // Subtract the items rarity from 101,
    // generating 100 occurences for the most common
    // and 1 occurence for the most rare
    $occurrences = 101 - $value['rarity'];
    for ($i = 0; $i < $occurrences; $i++) { 

        // Add the items key $occurrences times
        array_push($pool, $key);
    }
}

$weighed_item = $items[array_rand($pool)];

【讨论】:

    猜你喜欢
    • 2012-02-08
    • 2019-11-14
    • 1970-01-01
    • 1970-01-01
    • 2013-12-03
    • 2020-04-17
    • 1970-01-01
    • 1970-01-01
    • 2019-08-22
    相关资源
    最近更新 更多