How to get a random value from 1 ~ N, but excluding a few specific values ​​in PHP?

rand(1,N)But excluding array(a,b,c,..),

Is there already a built-in function that I don’t know or do I need to implement it myself (how?)?

UPDATE

A qualified solution must have gold performance if the size is excluded arraylarge or not.

+5
source share
7 answers

There is no built-in function, but you can 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;
}

This is from my mind, so it can use polishing - but at least you cannot end up with an endless loop script, even hypothetically.

: , $exceptions - . randWithout(1, 2, array(1,2)) randWithout(1, 2, array(0,1,2,3)) (), $from - $to, .

$exceptions , sort($exceptions); .

Eye-candy: .

+15

, ; , , .

, :

  • , rand() mt_rand(),
    • rand() ,
    • , N , .
  • ,
+8

, , .

$numbers = array_diff(range(1, N), array(a, b, c));
// Either (not a real answer, but could be useful, depending on your circumstances)
shuffle($numbers); // $numbers is now a randomly-sorted array containing all the numbers that interest you
// Or:
$x = $numbers[array_rand($numbers)]; // $x is now a random number selected from the set of numbers you're interested in

, , , , .

+7

...

<?php

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

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

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

, , M = N - #of exceptions . , . php , sem-psudo.

  • Offset [] , Exceptions.
  • Offset [i] , i .
  • . , r, 0..M .
  • i , Offset[i] <= r < Offest[i+i]
  • r + i

, , , 0 1 . , Offset , .

+1

, , - , , .

$excludedData = array(); // This is your excluded number
$maxVal = $this->db->count_all_results("game_pertanyaan"); // Get the maximum number based on my database

$randomNum = rand(1, $maxVal); // Make first initiation, I think you can put this directly in the while > in_array paramater, seems working as well, it up to you
while (in_array($randomNum, $excludedData)) {
  $randomNum = rand(1, $maxVal);
}

$randomNum; //Your random number excluding some number you choose
Hide result
0

:

$all =  range($Min,$Max);
$diff = array_diff($all,$Exclude);
shuffle($diff );
$data = array_slice($diff,0,$quantity);
0

All Articles