What is the best way to randomize array order in PHP without using the shuffle () function?

I was asked this question at an interview. The interviewer and I did not agree on what the correct answer was. I am wondering if anyone has any data on this.

Update: I should have mentioned that using shuffle () was strictly forbidden ... sorry.

+3
source share
7 answers

You can use the Fisher-Yates shuffle .

+2
source
shuffle($arr);

:)

edit: ... , . . , PhD " " , - .

+4

, :

function randomize_array_1($array_to_randomize) {
    $new_array = array();
    while (count($array_to_randomize) > 0) {
        $rand_num = rand(0, count($array_to_randomize)-1);
        $extracted = array_splice($array_to_randomize, $rand_num, 1);
        $new_array[] = $extracted[0];
    }
    return $new_array;
}

:

function randomize_array_2($array_to_randomize) {
    usort($array_to_randomize, "rand_sort");
    return $array_to_randomize;
}
function rand_sort($a, $b) {
    return rand(-1, 1);
}

( 1000 000 ), . , , , . :

randomize_array_1:
    [2, 3, 1] => 166855
    [2, 1, 3] => 166692
    [1, 2, 3] => 166690
    [3, 1, 2] => 166396
    [3, 2, 1] => 166629
    [1, 3, 2] => 166738

randomize_array_2:
    [1, 3, 2] => 147781
    [3, 1, 2] => 73972
    [3, 2, 1] => 445004
    [1, 2, 3] => 259406
    [2, 3, 1] => 49222
    [2, 1, 3] => 24615

, , , , .

+3

, , ( - )

:

for (i is 1 to n) Swap i with random position between 1 and n

:

for (i is 1 to n) Swap i with random position between i and n

, , .

+1

"" . ( // ) shuffle().

0

PHP → shuffle(). , , , , "".

http://computer.howstuffworks.com/question697.htm , .

0

: PHP array_rand() function

Given that the use of the shuffle function is forbidden, I would use it $keys = array_rand($myArray, count($myArray))to return an array of keys from $myArrayrandomly. From there, it should just be to collect them into a new array that has been randomized. Sort of:

$keys = array_rand($myArray, count($myArray));
$newArray = array();

foreach ($keys as $key) {
$newArray[$key] = $myArray[$key];
}
0
source

Source: https://habr.com/ru/post/1696893/


All Articles