Ruby,如何将一个数组混合到另一个数组中

fgu*_*len 2 ruby arrays sorting

两个阵列:

a1 = ["a", "b", "c", "d", "e", "f"]
a2 = [1, 2, 3]
Run Code Online (Sandbox Code Playgroud)

如何插入a2a1,保持A2顺序,但随机指标A1

saw*_*awa 6

(0..a1.length).to_a.sample(a2.length).sort
.zip(a2)
.reverse
.each{|i, e| a1.insert(i, e)}
Run Code Online (Sandbox Code Playgroud)


bhe*_*mar 5

这是我更新的答案:

a1 = ["a", "b", "c", "d", "e", "f"]
a2 = [1,2,3]

# scales to N arrays by just adding to this hash
h = { :a1 => a1.dup, :a2 => a2.dup }
# => {:a1=>["a", "b", "c", "d", "e", "f"], :a2=>[1, 2, 3]}

# Create an array of size a1+a2 with elements representing which array to pull from
sources = h.inject([]) { |s,(k,v)| s += [k] * v.size }
# => [:a1, :a1, :a1, :a1, :a1, :a1, :a2, :a2, :a2]

# Pull from the array indicated by the hash after shuffling the source list
sources.shuffle.map { |a| h[a].shift }
# => ["a", "b", 1, "c", 2, "d", "e", 3, "f"]
Run Code Online (Sandbox Code Playgroud)

算法归功于我的同事Ryan.

老答案没有保留两种顺序

a1.inject(a2) { |s,i| s.insert(rand(s.size), i) }
Run Code Online (Sandbox Code Playgroud)

使用a2作为目标,在a2的随机偏移量处从a1插入a2中的每个值.

  • 所以你不需要保留a1的订单? (2认同)