Home > Article > Backend Development > How to avoid generating adjacent duplicate elements when PHP arrays are shuffled?
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.
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:
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; }
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!