【问题标题】:Get n number of random values from an array and prevent consecutively repeated values从数组中获取n个随机值并防止连续重复值
【发布时间】:2022-11-01 16:56:28
【问题描述】:
我想填充一个包含从输入数组中随机抽取的值的结果数组,但结果数组不能有两个相同的连续值。
附加规则:
- 值的输入数组将仅包含唯一值,并且将至少具有两个值,以确保可以填充所需的结果数组。
- 随机值的数量可能大于或小于输入数组的大小。
- 如果随机值的数量大于输入数组的大小,则结果数组不得要求使用输入中的所有值。换句话说,随机选择的值不能偏向于均匀分布。
样本输入:
$array = ['one', 'two', 'three', 'four'];
$n = 10;
可能的有效结果的非详尽列表:
-
["three","one","three","one","two","one","four","one","three","four"]
-
["four","three","two","one","two","four","one","three","two","one"]
-
["two","four","three","one","two","one","four","two","three","one"]
这个问题的灵感来自this deleted question,它很难以明确的规则和期望提出这个问题。
【问题讨论】:
标签:
php
arrays
random
duplicates
filtering
【解决方案1】:
为了保证两个连续的值不相同,请跟踪前一个值(或其键)并将其作为当前迭代的可能随机值删除。将随机值推入结果数组,然后更新“前一个”变量。
array_diff_key() 可用于在调用 array_rand() 返回随机密钥之前排除特定密钥。
代码:(Demo) (Reduced alternative) (The ugly version)
$lastIndex = -1;
$result = [];
for ($x = 0; $x < $n; ++$x) {
$key = array_rand(array_diff_key($array, [$lastIndex => null]));
$result[] = $array[$key];
$lastIndex = $key;
}
echo PHP_EOL . json_encode($result);
或者,您可以使用unset() 排除先前的随机值,但重要的是不要修改原始数组,否则可能没有足够的值来填充结果数组。修改输入数组的副本即可。
代码:(Demo)
$lastIndex = -1;
$result = [];
for ($x = 0; $x < $n; ++$x) {
$copy = $array;
unset($copy[$lastIndex]);
$key = array_rand($copy);
$result[] = $copy[$key];
$lastIndex = $key;
}
echo PHP_EOL . json_encode($result);