伪随机化数组,其中相似的值不是连续的


Pseudo-randomize an array whereby similar values are not consecutive

我有一个数组,其中相似的值非常接近。喜欢:

1: Apple 2: Big Apple 3: Small Apple 4: Green Apple 5: Orange 6: Small Orange 7: Ripe Orange

等。

如果我在上面调用随机播放,排列可能会更改为:

1: Apple  3: Small Apple 5: Orange 4: Green Apple  6: Small Orange 2: Big Apple 7: Ripe Orange

如您所见,大多数苹果仍然在一起。当有 10 个类似类型的元素时,情况会变得更糟。有没有办法正确随机化每个值的位置?多次调用随机播放怎么样。还有其他更好的方法吗?

假设程序是从每个项目的最后一个单词中学习类型,这就是解决方案。(如果没有,只需更改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);

这是您需要的工作示例:

public function shuffle_assoc(&$array) {
    $keys = array_keys($array);
    shuffle($keys);
    foreach($keys as $key) {
        $new[$key] = $array[$key];
    }
    $array = $new;
    return true;
}
$fruits = array(
    1 => 'Apple ',
    2 => 'Big Apple ',
    3 => 'Small Apple ',
    4 => 'Green Apple ',
    5 => 'Orange ',
    6 => 'Small Orange ',
    7 => 'Ripe Orange',
);
shuffle_assoc($fruits);
echo "<pre>"; var_dump($fruits); die;