arrays - 带距离限制的数组shuffle算法

标签 arrays algorithm random permutation shuffle

例如,我有以下数组:

array numbers = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9};

我想打乱这个数组。但有一个距离限制:每个元素的新位置必须从 old_position - nold_position + n

例如,如果n = 4,那么这个数组对我有好处:

array new_numbers = {2, 3, 4, 0, 1, 6, 5, 8, 9, 7}

我试图想出一些算法。但我没有成功。

最佳答案

这里有一些可能有帮助的伪代码。请注意,该算法的重点是遵守距离规则,从而牺牲了过程中的均匀性*。

choose a random array index (call it "i" )
there's number at array[i] (call it "A")
set "count" to 0
for each "j" such that array[j] is a valid location for "A"
{
    there's a number at array[j] (call it "B")
    if ( "B" can be legally moved to array[i] )
        increment "count" 
}
generate a random number between 0 and count-1
find the index "j" that corresponds to that random number
swap array[i] with array[j]

repeat the above sequence a satisfactory number of times

* 在我看来,问题定义需要非均匀分布,因为例如,数组开头和结尾的值比数组中间的值具有更少的合法位置。因此,尝试开发一种可证明统一的算法似乎是一件愚蠢的事情。

关于arrays - 带距离限制的数组shuffle算法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27050850/

相关文章:

c# - 如何在 Azure 辅助角色中生成安全随机数?

OpenCV 随机森林 : Setting a random seed

jquery - 通过在表格上拖动来提醒选定的单元格计数

JavaScript - 遍历对象以查找特定键值

algorithm - 通过网络传输手写信息

algorithm - 区间(图论)算法讲解

java - 每次用户单击按钮时从 txt 或 CSV 文件中随机选择记录/行的最佳方法是什么?

javascript - 在 Javascript 中创建一个包含树元素的数组

javascript - 将数组表中的数据输入到列表中

python - 在 Perl 中寻找欧拉路径