-1

我想交错两个数组而不完全交替它们。例如,给定:

a = [1,2,3,4,5,6,7,8,9]
b = ['a','b','c']

我想收到f = [1,2,'a',3,4,'b',5,6,'c',7,8,9]作为输出。我想要b. 中每两个元素的一个元素a

一个解决方案似乎是:

a = [1,2,3,4,5,6,7,8,9]
b = ['a','b','c']

even, odd = a.partition.each_with_index{ |_, i| i.even? }
res = even.zip(odd,b)
res = res.flatten.reject(&:blank?)
#=> [1, 2, "a", 3, 4, "b", 5, 6, "c", 7, 8, 9]

但我对这个解决方案并不感到兴奋。有任何想法吗?

4

3 回答 3

4
a.each_slice(2).zip(b).flatten
#=> [1, 2, "a", 3, 4, "b", 5, 6, "c"] 
于 2016-07-08T14:51:06.130 回答
0

您可以尝试以下操作(对于您提供的两个示例):

b.zip(a.each_slice(2)).map(&:reverse).flatten
# => [1, 2, "a", 3, 4, "b", 5, 6, "c"]

示范

于 2016-07-08T14:50:58.287 回答
0

这适用于任何大小(包括)的数组a,并确保合并数组中的元素序列的长度最多相差一个。从when 开始的序列也是如此。 bb.size > a.sizeabb.size > a.size

def insert_em(a,b)
  b.size <= a.size ? recurse(a,b) : recurse(b,a)
end

def recurse(a,b)
  i = a.size/(b.size+1)
  b.size == 1 ? a[0,i] + b + a[i..-1] :
    [*a[0,i], b.first].concat(recurse(a[i..-1], b[1..-1]))
end

a = [1,2,3,4,5,6,7,8,9]

insert_em a, ['a']
  #=> [1, 2, 3, 4, "a", 5, 6, 7, 8, 9] 
insert_em a, ['a','b']
  #=> [1, 2, 3, "a", 4, 5, 6, "b", 7, 8, 9] 
insert_em a, ['a','b','c']
  #=> [1, 2, "a", 3, 4, "b", 5, 6, "c", 7, 8, 9] 
insert_em a, ['a','b','c','d']
  #=> [1, "a", 2, 3, "b", 4, 5, "c", 6, 7, "d", 8, 9] 
insert_em a, ['a','b','c','d','e']
  #=> [1, "a", 2, "b", 3, "c", 4, 5, "d", 6, 7, "e", 8, 9] 
insert_em a, ['a','b','c','d','e','f']
  #=> [1, "a", 2, "b", 3, "c", 4, "d", 5, "e", 6, 7, "f", 8, 9] 
insert_em a, ['a','b','c','d','e','f','g']
  #=> [1, "a", 2, "b", 3, "c", 4, "d", 5, "e", 6, "f", 7, "g", 8, 9] 
insert_em a, ['a','b','c','d','e','f','g','i']
  #=> [1, "a", 2, "b", 3, "c", 4, "d", 5, "e", 6, "f", 7, "g", 8, "i", 9] 
insert_em a, ['a','b','c','d','e','f','g','i','j']
  #=> ["a", 1, "b", 2, "c", 3, "d", 4, "e", 5, "f", 6, "g", 7, "i", 8, "j", 9] 
insert_em a, ['a','b','c','d','e','f','g','i','j','k']
  #=> ["a", 1, "b", 2, "c", 3, "d", 4, "e", 5, "f", 6, "g", 7, "i", 8, "j", 9, "k"] 
insert_em a, ['a','b','c','d','e','f','g','i','j','k','l']
  #=> ["a", 1, "b", 2, "c", 3, "d", 4, "e", 5, "f", 6, "g", 7, "i", 8, "j", 9, "k", "l"] 
于 2016-07-08T21:07:00.550 回答