dqnz43863 2010-07-22 06:44
浏览 24
已采纳

根据稀有度创建“卡片组”

I have an array of images. Each image has a "rarity" key that tells me whether it's "common", "uncommon", or "rare". So for instance, the array might look something like this:

Array
(
    [0] => Array
        (
            [image] => photo1.jpg
            [rarity] => common
        )

    [1] => Array
        (
            [image] => photo2.jpg
            [rarity] => uncommon
        )
    .
    .
    .

    [x] => Array
        (
            [image] => photo(x).jpg
            [rarity] => rare
        )
)

I want to select 'y' number of images from the list, almost like creating a deck of cards, but with images instead. The rarity, of course, defines how likely that card will be selected. How do I go about doing this? I figure I start with array_rand(), but am stuck as to where to go with it.

EDIT FOR CLARIFICATION: Each image in the array can only occur in the final deck once.

  • 写回答

5条回答 默认 最新

  • dongtuan1594 2010-07-22 06:57
    关注

    Here's my attempt. In $chances you have to define the chances that a common, uncommon or rare card will be chosen to appear in a deck as an int between 0-100. Also you have to provide the deck size.

    Presenting an answer where the cards are unique and cannot appear multiple times in the same deck:

    $cards = array(/* your array from above */);
    $deck = array();
    $deck_size = 52;
    
    $chances = array('common' => 90, 'uncommon' => 30, 'rare' => 5);
    $max_attempts = 3;
    $tmp_cards = $cards; // copied
    
    while(count($deck) < $deck_size) {
      $roll = rand(0, 100);
    
      for($a = 0; $a < $max_attempts; $a++) {
        $index = array_rand($tmp_cards);
        $card = $tmp_cards[$index];
        $rarity = $card['rarity'];
        $image = $card['image'];
    
        if(isset($deck[$image])) {
          continue;
        }
    
        if($roll <= $chances[$rarity]) {
          // if the roll is lower than the required probability
          // we can put this card in
          $deck[$image] = $card;
          unset($tmp_cards[$index]); // delete the card so it's not picked again
          break;
        }
      }
    }
    
    $deck = array_values($deck);
    

    Update

    Improved the code and provided definite exits to all branches.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(4条)

报告相同问题?

悬赏问题

  • ¥15 微信小程序协议怎么写
  • ¥15 c语言怎么用printf(“\b \b”)与getch()实现黑框里写入与删除?
  • ¥20 怎么用dlib库的算法识别小麦病虫害
  • ¥15 华为ensp模拟器中S5700交换机在配置过程中老是反复重启
  • ¥15 java写代码遇到问题,求帮助
  • ¥15 uniapp uview http 如何实现统一的请求异常信息提示?
  • ¥15 有了解d3和topogram.js库的吗?有偿请教
  • ¥100 任意维数的K均值聚类
  • ¥15 stamps做sbas-insar,时序沉降图怎么画
  • ¥15 买了个传感器,根据商家发的代码和步骤使用但是代码报错了不会改,有没有人可以看看