如何从1〜N中获得一个随机值,但在PHP中排除几个特定值呢? [英] How to get a random value from 1~N but excluding several specific values in PHP?

查看:57
本文介绍了如何从1〜N中获得一个随机值,但在PHP中排除几个特定值呢?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

rand(1,N),但不包括array(a,b,c,..)

是否已经有一个我不知道的内置函数,或者我必须自己实现(如何?)?

is there already a built-in function that I don't know or do I have to implement it myself(how?) ?

更新

无论excluded array的大小是否大,合格的解决方案都应该具有黄金性能.

The qualified solution should have gold performance whether the size of the excluded array is big or not.

推荐答案

没有内置函数,但是您可以做到这一点:

No built-in function, but you could do this:

function randWithout($from, $to, array $exceptions) {
    sort($exceptions); // lets us use break; in the foreach reliably
    $number = rand($from, $to - count($exceptions)); // or mt_rand()
    foreach ($exceptions as $exception) {
        if ($number >= $exception) {
            $number++; // make up for the gap
        } else /*if ($number < $exception)*/ {
            break;
        }
    }
    return $number;
}

那是我的头上的事,所以它可以使用抛光-但至少您不能陷入无限循环的情况,甚至是假设的情况.

That's off the top of my head, so it could use polishing - but at least you can't end up in an infinite-loop scenario, even hypothetically.

注意:如果$exceptions 耗尽您的范围,该功能就会中断-例如显然,调用randWithout(1, 2, array(1,2))randWithout(1, 2, array(0,1,2,3))不会产生任何有意义的结果,但是在那种情况下,返回的数字将超出$from-$to范围,因此很容易捕获.

Note: The function breaks if $exceptions exhausts your range - e.g. calling randWithout(1, 2, array(1,2)) or randWithout(1, 2, array(0,1,2,3)) will not yield anything sensible (obviously), but in that case, the returned number will be outside the $from-$to range, so it's easy to catch.

如果保证已经对$exceptions进行了排序,则可以删除sort($exceptions);.

If $exceptions is guaranteed to be sorted already, sort($exceptions); can be removed.

眼睛糖果:算法的某种简约可视化方式.

这篇关于如何从1〜N中获得一个随机值,但在PHP中排除几个特定值呢?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆