在Ruby中如何将数组[1,2,3]映射到[1,1,2,2,3,3]?

在Ruby中如何将数组[1,2,3]映射到[1,1,2,2,3,3]?,ruby,Ruby,我正在寻找映射阵列的最快方法: [1,2,3] 到 我最终得到了下面这样的结果。但这不是我需要的 [1,2,3].map { |n| [n,n] } => [[1, 1], [2, 2], [3, 3]] 您可以尝试flat\u map arr.flat_map { |n| [n, n] } # => [1, 1, 2, 2, 3, 3] 虽然Bartek的答案完全正确,但更通用的方法是映射数组 [a, b, c] 到 将是: MAPPER = ->(arr, n)

我正在寻找映射阵列的最快方法:

[1,2,3]

我最终得到了下面这样的结果。但这不是我需要的

[1,2,3].map { |n| [n,n] } => [[1, 1], [2, 2], [3, 3]] 

您可以尝试
flat\u map

arr.flat_map { |n| [n, n] } # => [1, 1, 2, 2, 3, 3]

虽然Bartek的答案完全正确,但更通用的方法是映射数组

[a, b, c]

将是:

MAPPER = ->(arr, n) { arr.flat_map { |e| [e] * n } } 
MAPPER.([1, 2, 3], 2)
#⇒ [1, 1, 2, 2, 3, 3]

假设OP要求的是最快的,他指的是计算。一些基准:

require 'fruity'
arr = [1, 2, 3]
MAPPER = ->(ar, n) { ar.flat_map { |e| [e] * n } }
compare do
  barteck_gladys {ar = arr.dup; ar.flat_map{|n| [n,n]} }
  mudasobwa      {ar = arr.dup; MAPPER.(ar, 2)}
end

#Running each test 1024 times. Test will take about 1 second.
#barteck_gladys is faster than mudasobwa by 2x ± 0.1        
对于
arr=(1..100)。对于a

#Running each test 32 times. Test will take about 1 second.
#barteck_gladys is faster than mudasobwa by 2x ± 1.0
#Running each test 4 times. Test will take about 1 second.
#barteck_gladys is faster than mudasobwa by 2x ± 0.1
对于
arr=(1…1000)。到a

#Running each test 32 times. Test will take about 1 second.
#barteck_gladys is faster than mudasobwa by 2x ± 1.0
#Running each test 4 times. Test will take about 1 second.
#barteck_gladys is faster than mudasobwa by 2x ± 0.1
您也可以尝试:

Array.new(2){[1,2,3]}.flatte.sort#=>[1,1,2,2,3,3]

这种方法非常灵活,因为您现在可以轻松增加
数组中每个整数的出现次数,例如


Array.new(3){[1,2,3]}.flatte.sort#=>[1,1,1,2,2,2,3,3]

如果数组是
[3,2,1]
@ndn很棒的点,那么我的解决方案的结果将是不正确的,而mudasowba和bartek的则是正确的。我想我会删除我的解决方案,只使用正确的答案更新基准测试。感谢它们的
arr.zip(arr)。用对象([]){n,a | a展平
arr.each_