Welcome to collectivesolver - Programming & Software Q&A with code examples. A website with trusted programming answers. All programs are tested and work.

Contact: aviboots(AT)netvision.net.il

Buy a domain name - Register cheap domain names from $0.99 - Namecheap

Scalable Hosting That Grows With You

Secure & Reliable Web Hosting, Free Domain, Free SSL, 1-Click WordPress Install, Expert 24/7 Support

Semrush - keyword research tool

Boost your online presence with premium web hosting and servers

Disclosure: My content contains affiliate links.

39,903 questions

51,834 answers

573 users

How to select N reservoir items randomly from an array in PHP

2 Answers

0 votes
function selectReservoir($arr, $N) {
    $size = count($arr);
    $reservoir = array();
    $items = 0;
    
    while ($items < $N) {
        $i = rand(0, $size);
        $found = false;
            
        for ($j = 0; $j < $items; $j++) {
            if (in_array($arr[$i], $reservoir)) {
                $found = true;
                break;
            }
        }
            
        if (!$found) {
            array_push($reservoir, $arr[$i]);
            $items++;
        }
    }
        
    return $reservoir;
}

$arr = array(4, 9, 14, 96, 13, 0, 3, 99, 19, 2, 80, 1, 7);
$N = 5;

$reservoir = selectReservoir($arr, $N);

print_r($reservoir);




/*
run:

Array
(
    [0] => 14
    [1] => 0
    [2] => 19
    [3] => 1
    [4] => 96
)

*/

 



answered Feb 4, 2024 by avibootz
0 votes
function selectReservoir($arr, $N) {
    $reservoir = array();
    
    shuffle($arr);
    
    $reservoir = array_slice($arr, 0, $N);
        
    return $reservoir;
}

$arr = array(4, 9, 14, 96, 13, 0, 3, 99, 19, 2, 80, 1, 7);
$N = 5;

$reservoir = selectReservoir($arr, $N);

print_r($reservoir);




/*
run:

Array
(
    [0] => 4
    [1] => 99
    [2] => 14
    [3] => 2
    [4] => 0
)

*/

 



answered Feb 4, 2024 by avibootz

Related questions

1 answer 110 views
2 answers 143 views
2 answers 120 views
2 answers 146 views
2 answers 133 views
...