rmn.nish
rmn.nish

Reputation: 889

Ruby array map(&:flatten) is causing a latency issue

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

Answers (2)

Marcin Kołodziej
Marcin Kołodziej

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

Getu
Getu

Reputation: 179

this GitHub is comparing I/O speed of several methods. Perhaps you might try that flat_map method to optimize your last operation.

Upvotes: 0

Related Questions