在再次选择相同元素之前选择具有保证间距的随机元素

问题描述 投票:0回答:1

我想从列表中选择随机元素,而不能连续重复同一元素两次。我希望在再次选择同一元素之间有一定数量的其他元素。此外,不可能100%预测下一个选择是什么。

我当前的解决方案是随机选择元素,直到我选择了全部元素的三分之一。然后,我随机选择其他元素的一半来获得另外三分之一。之后,我将前三分之一添加回其余元素并重复该过程。

这样,在重复元素之前,我保证的距离是元素总数的1/3。但是,我想有更大的间距。有什么方法可以实现而又不会使选择成为可预测的?

arrays random pascal
1个回答
0
投票

我无法为您提供Pascal的帮助,我没有副本,并且已有30多年没有使用它了,所以我不知道您可以访问哪些库。

顺便说一句,如果您拥有(或可以伪造)队列数据结构,那么您就可以按照先进先出的顺序存储内容。该任务相当简单。

  • 随机播放原始数组,然后从其末尾切出所需的“ spacing”元素数。
  • [通过随机生成索引从数组的N - spacing个项目中随机选择一个元素。
  • 对该项目执行任何操作,然后将其添加到队列中。
  • 将第一个元素弹出队列,并将其存储在您刚刚选择/使用的项目的位置。

Voila!最近使用的项目将存储在队列中,直到它们到达最前面为止,然后将它们循环到您要从中进行随机化的集合中。由于它们在队列的长度内不流通,因此可以保证间隔。

这里是在Ruby中,它几乎是伪代码。我也注释了一下。

ary = (1..10).to_a   # create an array "ary" containing the numbers 1 to 10
ary.shuffle!         # shuffle the array
spacing = ary.length / 3  # set the desired spacing as fraction of ary

# Now we'll slice the last "spacing" elements off into a queue,
#   starting at location ary.length - spacing
queue = ary.slice!(ary.length - spacing, spacing)
p ary, queue         # print the array and queue to show the random splitting

# Now we're set up with "spacing" random elements (from the shuffling)
# in a queue, and the rest still in "ary"
20.times do  # do the following 20 times for demo purposes
  index = rand(ary.length)    # Choose a random index in "ary",
  print ary[index]            # print it out,
  print ' '                   # and print a space after it.
  queue << ary[index]         # Now append it to the queue
  ary[index] = queue.shift    # and replace that location with the first element popped from the queue
end
puts    # put a new-line at the end of the printed values

产生例如:

[7, 2, 3, 8, 6, 10, 5]
[9, 1, 4]
5 7 8 3 5 2 9 4 1 7 3 6 1 5 3 2 4 6 1 7 

第一行是切片后的改组数组,第二行是切片值的队列,第三行是该算法20次迭代的结果。请注意,在其先前用法的3内没有元素发生。

© www.soinside.com 2019 - 2024. All rights reserved.