dongxue9997 2014-07-03 00:15
浏览 35
已采纳

不在数组中的随机数[重复]

This question is an exact duplicate of:

I have an array of numbers and I need to make a random number then check if that number is not in the array, If it is make another random number and then check that number to see if its in the array.

example.

array = 1, 2, 4, 5, 7
rand(1, 7) = 3 or 6

if rand(1, 7) = 1, 2, 4, 5 or 7 it would run again until it returned 3 or 6.

anyone know how to do this in php?

</div>
  • 写回答

2条回答 默认 最新

  • douqingji3026 2014-07-03 00:20
    关注

    You may simply generate a random number and check if it is already in the array

    $in = [1, 4, 7, 9];
    do {
        $rand = rand($min, $max);
    } while(in_array($rand, $in));
    
    echo $rand, ' is random, but not in the input array';
    

    The above code generates a random integer that is insides the bounds defined in $min and $max. If the value already exists inside the array a new random value is fetched and compared to the input array.

    Note: While the above is the minimal working code you may create an endless loop if your input array contains all possible values(Thanks @Action Dan). You didn't state in your question whether this is possible or not. If it is possible you need to work around this. Either by limiting the the maximum tries or validating the input array before and issuing an error message or increasing the 2nd parameter of rand.

    Example(validating, only recommended for smaller arrays):

    $in = [1,2,3,4,5];
    $min = 1;
    $max = 5;
    if(range($min, $max) === $in) {
        echo 'No possible value in range';
        exit;
    }
    // code from above
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥30 截图中的mathematics程序转换成matlab
  • ¥15 动力学代码报错,维度不匹配
  • ¥15 Power query添加列问题
  • ¥50 Kubernetes&Fission&Eleasticsearch
  • ¥15 有没有帮写代码做实验仿真的
  • ¥15 報錯:Person is not mapped,如何解決?
  • ¥15 c++头文件不能识别CDialog
  • ¥15 Excel发现不可读取的内容
  • ¥15 关于#stm32#的问题:CANOpen的PDO同步传输问题
  • ¥20 yolov5自定义Prune报错,如何解决?