我有一个数组,其中相似的值靠得很近。喜欢:
1: Apple 2: Big Apple 3: Small Apple 4: Green Apple 5: Orange 6: Small Orange 7: Ripe Orange
等等
如果我对其调用 shuffle,排列可能会变为:
1: Apple 3: Small Apple 5: Orange 4: Green Apple 6: Small Orange 2: Big Apple 7: Ripe Orange
如您所见,大部分苹果仍然在一起。当有 10 个同类元素时,情况会变得更糟。有没有办法正确随机化每个值的位置?多次调用 shuffle 怎么样?还有其他更好的方法吗?
最佳答案
假设程序是从每个项目的最后一个单词中学习种类,这就是解决方案。 (如果不是,只需更改kind_of()
函数中的逻辑即可)
<?php
// learn what kind if item is it
function kind_of($item) {
$words = explode(' ', $item);
return array_pop($words);
}
// reorganize as 2-dimensional array
function by_kind($input) {
$output = array();
foreach ($input as $item) {
$output[kind_of($item)][] = $item;
}
return $output;
}
$input = array(
'Orange',
'Apple',
'Big Apple',
'Small Orange',
'Small Apple',
'Ripe Orange',
'Green Apple',
);
// arrange the items in 2-dimensional by_kind array
// then shuffle each second level arrays
$by_kind = by_kind($input);
ksort($by_kind); // sort by key (kind name)
$shuffled_by_kind = array_map(function ($kind_items) {
shuffle($kind_items);
return $kind_items;
}, $by_kind);
// merge the second level arrays back to 1 array
$result = call_user_func_array('array_merge', array_values($shuffled_by_kind));
// see output
var_dump($result);
关于php - 伪随机化一个数组,其中相似的值不连续,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30907256/