是否有一种简单的方法可以在随机位置压缩2个数组并保持原始顺序?
例如
a=[0,1,2,3,4,5,6,7,8,9,10]
b=["one","two","three","four"]
和一个0到5的随机数rand(5)
zipped = [0,"one",1,2,3,"two",4,"three",5,6,7,8,"four",9,10]
并且随机序列将1,3,1,4
作为将“b”的每个元素“压缩”到
我能做的最好的事情是
i=0
merged=a
b.each do |x|
rnd = rand(5)
merged.insert(i+rnd,x)
i=i+rnd
end
答案 0 :(得分:4)
此版本将提供平衡的混洗,插入不会偏向数组的任何一端。
def ordered_random_merge(a,b)
a, b = a.dup, b.dup
a.map{rand(b.size+1)}.sort.reverse.each do |index|
b.insert(index, a.pop)
end
b
end
答案 1 :(得分:0)
以下是更具功能性的Mark Hubbart's approach变体。
MergeTuple = Struct.new:place,:value
def ordered_random_merge( merge_to, merge_from )
merge_from.
map { |e| MergeTuple[ rand( merge_to.size+1 ), e ] }.
sort_by { |mt| - mt.place }.
each_with_object( merge_to.dup ) { |mt, merged| merged.insert(mt.place, mt.value) }
end