在重复元素的同时用n个数字扩展数组

时间:2015-08-04 18:19:48

标签: ruby

如果我有这样的数组

[1,2,3]*2 
#=> [1,2,3,1,2,3,1,2,3]

但我想做到一定的长度,长度是原始数组的1.5,最好是一行

[1,2,3].size = 3
[1,2,3,1,2] or something like this

2 个答案:

答案 0 :(得分:3)

a = [1, 2, 3]
a.cycle.first(a.length.*(1.5).round)
# => [1, 2, 3, 1, 2]

答案 1 :(得分:3)

以下是一行中的简单解决方案

 ([1,2,3]*2).tap {|a| a.pop(a.size - (a.size / 2 * 1.5)) }
 #=> [1,2,3,1,2]

细分

 ([1,2,3]*2)
 #=> [1,2,3,1,2,3]
 #`Object#tap` will yield the object itself to the block 
 #so a is [1,2,3,1,2,3]
 .tap { |a|
   #pop is mutating so we are dropping the elements that are after 
   #the array size minus 1.5 times the original array of [1,2,3]  
   #so this becomes [1,2,3,1,2,3].pop(6 - 4.5)
   #pop will use the Integer value so this becomes (6 - 4.5).to_i (which is 1)   
   a.pop(a.size - (a.size / 2 * 1.5)) 
 }  
 #=> [1,2,3,1,2]

我更喜欢@ sawa使用枚举器的答案,但确实需要2行。

此外,这似乎很奇怪,如果您提供有关实际问题的更多信息,可能有更好的方法来解决这个问题。

更新:我认为这有点清洁

类似的概念使用tap但不需要乘法然后除

[1,2,3].tap {|a| a.concat(a.take((a.size * 0.5).round)) }
#=> [1,2,3,1,2]

细分:

#concat will take an array and append the elements to the end of the reciever
#so here we are taking half of the original elements (rounded up) 
#and appending them to the original array
[1,2,3].tap {|a|
  #a.take(3 * 0.5) with round becomes a.take(2)
  #a.concat([1,2])
  # => [1,2,3,1,2] 
  a.concat(a.take((a.size * 0.5).round)) 
}
#=> [1,2,3,1,2]

如果您知道所需的元素数量,那么其他选项会变得非常简单

[1,2,3].cycle.take(5)
#=> [1,2,3,1,2]