2

两个数组:

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

如何插入a2a1保持a2 顺序但在a1的随机索引中?

4

5 回答 5

6
(0..a1.length).to_a.sample(a2.length).sort
.zip(a2)
.reverse
.each{|i, e| a1.insert(i, e)}
于 2013-02-05T17:33:52.257 回答
6

这是我的更新答案:

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"]

该算法的功劳归功于我的同事 Ryan。

旧答案不保留两者的顺序

a1.inject(a2) { |s,i| s.insert(rand(s.size), i) }

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

于 2013-02-05T17:36:11.453 回答
3

通过模拟真实的 shuffle 来保持两个数组的顺序,一旦将数组的元素插入到另一个数组中,下一个元素就不能放在它之前。

class Array
  def shuffle_into(array)
    n = 0
    self.each.with_object(array.dup) do |e, obj|
      i = rand(n..obj.size)
      obj.insert(i, e)
      n = i + 1
    end
  end
end

n = 0说不定能把周围的漂浮物清理干净。

例子:a2.shuffle_into(a1) => [1, "a", "b", "c", "d", 2, "e", "f", 3]

于 2013-02-05T19:26:44.680 回答
2

这个丑陋的废话完成了这项工作(没有弄乱任何数组顺序):

class Array
  def shuffle_into(ary)
    a1 = ary.dup
    a2 = dup
    Array.new(a1.size + a2.size) do
      [true, false].sample ? (a1.shift || a2.shift) : (a2.shift || a1.shift)
    end
  end
end
于 2013-02-05T18:30:50.790 回答
-1

a1.zip((a2 + [nil] * (a1.size - a2.size)).shuffle).flatten.compact

顺便说一句,可能的重复:在随机位置用 ruby​​ 压缩 2 个数组

于 2013-02-05T17:43:01.377 回答