荏苒2阵列中的红宝石在随机位置 [英] Zipping 2 arrays in ruby in random locations
本文介绍了荏苒2阵列中的红宝石在随机位置的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
有没有一种简单的方法来压缩在随机位置2阵列和保持其原有的秩序
例如:
A = [0,1,2,3,4,5,6,7,8,9,10]
B = [一,二,三,四]
和从0到5的随机数与兰特(5)
压缩= [0,一,1,2,3,两节; 4,三,5,6,7,8,四个一,9 10]
和随机系列将 1,3,1,4
的位置在哪里ZIPB的每个元素成
我能做到的最好的是
I = 0
合并=一
b.each做| X |
RND =兰特(5)
merged.insert(RND我+ X)
I = I + RND
结束
解决方案
这个版本将提供一个平衡的洗牌,以插入不偏向阵列的两端。
DEF ordered_random_merge(A,B)
A,B = a.dup,b.dup
。a.map {兰特(b.size + 1)} sort.reverse.each办|首页|
b.insert(索引,a.pop)
结束
b
结束
Is there an easy way to zip 2 arrays in random locations and keep their original order?
for example
a=[0,1,2,3,4,5,6,7,8,9,10]
b=["one","two","three","four"]
and a random number from 0 to 5 with rand(5)
zipped = [0,"one",1,2,3,"two",4,"three",5,6,7,8,"four",9,10]
and the random series would be 1,3,1,4
as location to where to "zip" each element of b into a
The best I could do is
i=0
merged=a
b.each do |x|
rnd = rand(5)
merged.insert(i+rnd,x)
i=i+rnd
end
解决方案
This version will give a balanced shuffling, with insertions not biased to either end of the array.
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
这篇关于荏苒2阵列中的红宝石在随机位置的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文