【问题标题】:Using unique random numbers for a switch statement对 switch 语句使用唯一的随机数
【发布时间】:2016-12-03 20:18:55
【问题描述】:

我需要一个函数或数组,它可以给我从 1 到 47 的随机数,所以我可以在下面的代码中使用它。

public function output($question_id, $solution) {
    $yes = ($GLOBALS['TSFE']->sys_language_uid == 0) ? 'Ja' : 'Oui';
    $no = ($GLOBALS['TSFE']->sys_language_uid == 0) ? 'Nein' : 'No';
    switch ($question_id) {
        case 1:
            $arg = array(
                'main_content' => $this->build_html(1, '01_0429_04_14_Psori_Arthro.jpg', $yes, $no, $solution)
            );
        break;
        case 2:
            $arg = array(
                'main_content' => $this->build_html(2, '02_0342_05_14_Psori_Arthropathie.jpg', $yes, $no, $solution),
            );
        break;
        case 3:
            $arg = array(
                'main_content' => $this->build_html(3, '03_0255_05_14_Psori_Arthropathie.jpg', $yes, $no, $solution),
            );
        break;
    }
}

示例

这个

case 1:
    $arg = array(
        'main_content' => $this->build_html(1, '01_0429_04_14_Psori_Arthro.jpg', $yes, $no, $solution)
    );

应该看起来像这样:

case $random_id:
    $arg = array(
        'main_content' => $this->build_html($random_id, '01_0429_04_14_Psori_Arthro.jpg', $yes, $no, $solution)
    );

这意味着,函数build_html 的每个案例和每个第一个参数都应该获得一个唯一随机ID。

当然我可以使用rand(),但是我很可能会得到重复的值。

任何帮助将不胜感激!

【问题讨论】:

  • 您是否特别需要 1 到 47 之间的随机数,或者更确切地说是 1 到 47 之间的非重复数字?
  • @Andrew 我需要 47 个随机数,因为我有 47 个案例,每个案例都应该是唯一的。
  • 既然知道范围,为什么不直接做一个循环呢?从表面上看,您实际上并不需要 1 到 47 之间的随机数,而是需要 1 到 47 之间的数字。
  • 要从一组固定的元素中以随机顺序枚举而不重复,shuffle 集合。

标签: php random


【解决方案1】:

如下创建一个类:

class SamplerWithoutReplacement {
      private $pool;

      public __construct($min,$max) {
             $this->pool = range($min,$max);              
      }

      public function next() {
           if (!empty($this->pool)) {
               $nIndex = array_rand($this->pool);
               $value = $this->pool[$nIndex];
               unset($this->pool[$nIndex]);
               return $value;
           } 
           return null; //Or throw exception, depends on your handling preference
      }

}

将其用作:

 $sampler = new SamplerWithoutReplacement(1,47);
 //do things
 $value = $sampler->next();

$sampler 将在 1-47 之间随机抽取样本,而不会在池中替换它们,因此它们将是唯一的。

【讨论】:

    【解决方案2】:

    未经测试,但我认为它应该可以工作:

    $numbers = [];
    function genenerate_nr_not_in_list($list, $min = 1, $max = 47) {
        $number = rand($min, $max);
        while (false !== array_search($number, $list)) {
            $number = rand($min, $max);
        }
        return $number;
    }
    for ($i = 0; $i < 47; $i++) {
        $numbers[] = genenerate_nr_not_in_list($numbers);
    }
    

    使用此解决方案,您可以生成每个范围内的数字($min$max 参数)。但它至少应该与您需要的值的数量一样大 ($max)。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-05-08
      • 1970-01-01
      • 2015-09-14
      • 2016-09-19
      • 1970-01-01
      • 2019-06-15
      • 2013-09-03
      • 2014-08-11
      相关资源
      最近更新 更多