聘我网

新概念招聘3.0

如何实现1~N中取随机数,但排除某一些数?

vote up0vote downstar

rand(1,N)排除array(x,y,z,..)中的数,其中N可以非常大,但排除数组不会太大。

不要这种理论上可能死循环的解决:

function rand_except($min, $max, $excepting = array()) { 

    $num = mt_rand($min, $max); 

    return in_array($num, $excepting) ? rand_except($min, $max, $excepting) : $num; 
} 
 

1 个答复

vote up0vote downcheck
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  { 
            break; 
        } 
    } 
    return $number; 
} 

原理图:

alt text

链接

您的回答





不是您要找的问题? 浏览其他含有标签 的问题或者 自己问个.