Home  >  Article  >  Backend Development  >  How to avoid generating adjacent duplicate elements when PHP arrays are shuffled?

How to avoid generating adjacent duplicate elements when PHP arrays are shuffled?

王林
王林Original
2024-05-02 10:36:02732browse

PHP shuffle() may generate adjacent duplicate elements. To avoid this, you can use the following two methods: Use the a-Hash algorithm: generate a hash for each value and only keep the value corresponding to the unique hash value. Use mark and shuffle: Mark the used index and delete the marked index value before shuffling.

How to avoid generating adjacent duplicate elements when PHP arrays are shuffled?

PHP avoids adjacent duplicate elements when the array is shuffled

In PHP, use shuffle() It is a common requirement for functions to shuffle array order. However, this function may generate adjacent duplicate elements. To avoid this we can use the following:

Implementation:

  1. Use a-Hash:
function shuffle_array_avoid_adjacent_duplicates(array &$array) {
    $aHash = [];
    $result = [];
    foreach ($array as $key => $value) {
        $ah = md5($value);
        if (!isset($aHash[$ah])) {
            $aHash[$ah] = true;
            $result[] = $value;
        }
    }
    shuffle($result);
    return $result;
}
  1. Using marking and shuffling:
function shuffle_array_avoid_adjacent_duplicates(array &$array) {
    $marked = [];
    foreach ($array as $key => $value) {
        $marked[$key] = false;
    }
    while (count($marked)) {
        $key = array_rand($marked);
        $result[] = $array[$key];
        unset($marked[$key]);
        unset($array[$key]);
    }
    shuffle($result);
    return $result;
}

Practical example:

$array = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];

$shuffled_array = shuffle_array_avoid_adjacent_duplicates($array);

print_r($shuffled_array);

Output:

Array
(
    [0] => 5
    [1] => 2
    [2] => 9
    [3] => 10
    [4] => 7
    [5] => 4
    [6] => 3
    [7] => 8
    [8] => 6
    [9] => 1
)

The above code uses the a-Hash algorithm to avoid adjacent duplicate elements and generate a disordered array.

The above is the detailed content of How to avoid generating adjacent duplicate elements when PHP arrays are shuffled?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn