首页 > 解决方案 > 在再次选择相同元素之前选择具有保证间距的随机元素

问题描述

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

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

这样,在重复一个元素之前,我保证了总元素的 1/3 的距离。但是,我想要更大的间距。有没有办法在不使选择可预测的情况下实现这一目标?

标签: arraysrandompascal

解决方案


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

这样一来,如果您拥有(或可以伪造)队列数据结构,那么任务就相当简单了,这样您就可以按照先进先出的顺序存储事物。

  • 打乱原始数组,然后从它的末尾切出所需的“间距”数量的元素。
  • N - spacing通过随机生成索引从数组中的项目中随机选择一个元素。
  • 对该项目做任何你想做的事情,然后将其附加到队列中。
  • 从队列中弹出第一个元素并将其存储在您刚刚选择/使用的项目的位置。

瞧!最近使用过的项目存储在队列中,直到它们到达最前面,然后它们被回收到您正在随机化的集合中。由于它们在队列长度内没有流通,因此间距是有保证的。

这里是 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 内。


推荐阅读