Php random fill range

2019-09-11 11:30发布

问题:

I have this:

$numbers = range(1,52);
shuffle($numbers);

foreach($users as $user) {

    $uniqueRand = array_pop($numbers);

}

This give each user in my database a unique random number.

I have 15 users in total, is it somehow possible to fill the rest of the range from 1-32 and repeat the randoming so to say.

it looks like this now:

1   -  24
2   -  26
3   -  2
4   -  6
5   -  8
6   -  31
7   -  25
8   -  16
9   -  13
10  -  21
11  -  19
12  -  29
13  -  8
14  -  4
15  -  6

Just users with random numbers, is it possible the give those numbers which were not allocated to a user in the range again randomly a user until all numbers in the range are given?

回答1:

<?php

function f($userIds, $numbers)
{
    shuffle($numbers); // added
    $picks = array();

    foreach ($userIds as $id) {
        $picks[] = array('id' => $id, 'numbers' => array());
    }

    // Shuffle order of userIds. Give one number to each user. Repeat both steps
    // until all numbers are gone
    $n = count($userIds);
    $i = 0;
    while (!empty($numbers)) {
        if ($i % $n === 0) {
            shuffle($picks);
        }
        $picks[$i % $n]['numbers'][] = array_pop($numbers);
        $i++;
    }

    return $picks;
}

$picks = f(array(1, 2, 3, 4, 9, 12, 47, 50), range(1, 30));

foreach ($picks as $p) {
    printf("id %s: %s\n", $p['id'], implode(', ', $p['numbers']));
}

Will output something like:

id 47: 28, 22, 8, 6
id 1: 30, 17, 12, 5
id 12: 24, 16, 7, 4
id 9: 23, 19, 13, 3
id 50: 25, 18, 14, 2
id 3: 27, 15, 9, 1
id 4: 29, 20, 10
id 2: 26, 21, 11

Edit: Forgot something. You might want to shuffle() the numbers, too, to get a more random distribution. Added the line to the function.