假设我有两个数组:
a = ["Fruit", "Emu", "Color"]
b = ["Banana", "Name", "Orange"]
我想将b
数组值插入a
的随机位置。这两个数组的可能输出是:
c = ["Banana", "Fruit", "Emu", "Color", "Orange", "Name"]
此处,b
数组值将插入a
,但值序列
"Fruit"
→"Emu"
→"Color"
a
的没有受到阻碍。我怎样才能做到这一点?
答案 0 :(得分:6)
这可能会奏效:
a = [1, 2, 3]
b = [:foo, :bar, :baz]
b.each_with_object(a.dup) { |e, ary| ary.insert(rand(0..ary.size), e) }
#=> [:baz, 1, 2, :foo, :bar, 3]
dup
创建a
的副本,该副本作为ary
传递到块中,以及每个b
的元素rand
返回0
(数组开头)和ary.size
(数组结尾)之间的随机索引insert
将当前元素插入给定索引each_with_object
返回带有随机插入元素的复制数组答案 1 :(得分:1)
这是另一种方式:
def stuff_randomly(a,b)
sz_a = a.size
cpy_a = a.dup
(sz_a+b.size).times.to_a.shuffle.map do |i|
(i < sz_a) ? cpy_a.shift : b[i-sz_a]
end
end
a = [1, 2, 3]
b = [:foo, :bar, :baz]
10.times { p stuff_randomly(a,b) }
[:foo, 1, 2, 3, :bar, :baz]
[1, :baz, 2, :foo, 3, :bar]
[1, :foo, :bar, :baz, 2, 3]
[1, 2, 3, :foo, :bar, :baz]
[1, :bar, :foo, 2, 3, :baz]
[:foo, 1, :baz, 2, :bar, 3]
[:bar, 1, 2, 3, :foo, :baz]
[:bar, 1, :foo, :baz, 2, 3]
[1, 2, :baz, :bar, :foo, 3]
[1, :foo, :bar, 2, 3, :baz]
答案 2 :(得分:0)
我认为最简单的方法如下。
a = ["Fruit", "Emu", "Color"]
b = ["Banana", "Name", "Orange"]
b.each { |value| a.insert(rand(0..a.length), value) }
#=> ["Name", "Orange", "Fruit", "Emu", "Banana", "Color"]
对于b
的每个元素,将值插入随机索引a
。
这基本上是Stefan的答案,但没有each_with_object
方法。我认为这种方式稍微清洁,并提供相同的解决方案。