Reputation: 889
I have a multi-dimensional array as below
arr = [["2", "3", "1"], ["5", "2", "6", "1", "4", "3"], ["2", "5", "1", "3", "6", "4"], ["2", "3", "1"], ["2", "3", "1"], ["1", "2", "3"]]
I want to generate a combination and flatten it as below.
[["2", "5", "2", "2", "2", "1"], ["2", "5", "2", "2", "2", "2"], ["2", "5", "2", "2", "2", "3"], ["2", "5", "2", "2", "3", "1"], ["2", "5", "2", "2", "3", "2"], ["2", "5", "2", "2", "3", "3"],..., ["1", "3", "4", "1", "1", "3"]]
The code is as below
comb = arr.inject(&:product)
flat_arr = comb.map(&:flatten)
flat_arr = comb.map(&:flatten)
is taking around 5ms-8ms
. I have many such arrays and it is causing a latency issue. Is there a way to reduce it?
Upvotes: 4
Views: 172
Reputation: 5313
You could get rid of flattening altogether,
Benchmark.bm(7) do |bm|
bm.report("inject") { n.times { arr.inject(&:product).map(&:flatten) }}
bm.report("product splat") { n.times { arr[0].product(*arr[1..-1]) } }
end
user system total real
inject 3.390163 0.003636 3.393799 ( 3.397507)
product splat 0.514577 0.000000 0.514577 ( 0.514595)
As
arr.inject(&:product).map(&:flatten) == arr[0].product(*arr[1..-1])
=> true
Upvotes: 3