具有距离限制的阵列混洗算法

时间:2014-11-20 22:30:24

标签: 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}

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

1 个答案:

答案 0 :(得分:2)

这是一些可能有用的伪代码。注意,该算法的重点是符合距离规则,牺牲了过程中的均匀性*。

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

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