Question

I have two Ruby arrays of days and trips, and the days of week as indicated below:

days = ["Monday", "Tuesday", "Wednesday","Thursday","Friday","Saturday","Sunday"]

And the bus time schedule here:

trips = [
  "2.35pm","4.50pm","7.00pm",
  "2.35pm","4.50pm","7.00pm",
  "2.35pm","4.50pm","7.00pm",
  "2.35pm","4.50pm","7.00pm",
  "2.35pm","4.50pm","7.00pm",
  "2.35pm","4.50pm","7.00pm",
  "2.35pm","4.50pm","7.00pm"
]

The result am trying to achieve is this:

Bus-times = [
  "Monday","2.35pm","4.50pm","7.00pm",
  "Tuesday","2.35pm","4.50pm","7.00pm",
  "Wednesday","2.35pm","4.50pm","7.00pm",
  "Thusday","2.35pm","4.50pm","7.00pm",
  "Friday","2.35pm","4.50pm","7.00pm",
  "Saturday","2.35pm","4.50pm","7.00pm",
  "Sunday""2.35pm","4.50pm","7.00pm"
]

I've looked at interleaving, and zip only returns the first result if i don't write my own function. What other options do I have?

Was it helpful?

Solution

bus_times = days.zip(trips.each_slice(3)).flatten

or if you want to keep them as an array of arrays:

bus_times = days.zip(trips.each_slice(3)).map(&:flatten)

OTHER TIPS

here is the code :

trips.each_slice(3).flat_map.with_index(0){|a,i| a.unshift(days[i])}

or,

[days,trips.each_slice(3).to_a ].transpose.flatten 

output

[
    "Monday",
    "2.35pm",
    "4.50pm",
    "7.00pm",
    "Tuesday",
    "2.35pm",
    "4.50pm",
    "7.00pm",
    "Wednesday",
    "2.35pm",
    "4.50pm",
    "7.00pm",
    "Thursday",
    "2.35pm",
    "4.50pm",
    "7.00pm",
    "Friday",
    "2.35pm",
    "4.50pm",
    "7.00pm",
    "Saturday",
    "2.35pm",
    "4.50pm",
    "7.00pm",
    "Sunday",
    "2.35pm",
    "4.50pm",
    "7.00pm"
]

Benchmark

require 'benchmark'

days = ["Monday", "Tuesday", "Wednesday","Thursday","Friday","Saturday","Sunday"]
trips= ["2.35pm","4.50pm","7.00pm","2.35pm","4.50pm","7.00pm","2.35pm","4.50pm","7.00pm","2.35pm","4.50pm","7.00pm","2.35pm","4.50pm","7.00pm","2.35pm","4.50pm","7.00pm","2.35pm","4.50pm","7.00pm"]


n = 50000
Benchmark.bm(7) do |x|
  x.report("ZIP")   { n.times{days.zip(trips.each_slice(3)).flatten} }
  x.report("MAP") { n.times{trips.each_slice(3).flat_map.with_index(0){|a,i| a.unshift(days[i])}} }
  x.report("TRANSPOSE")  { n.times{[days,trips.each_slice(3).to_a ].transpose.flatten} }
end

Result

              user     system      total        real
ZIP        0.800000   0.000000   0.800000 (  0.798833)
MAP        0.600000   0.000000   0.600000 (  0.597299)
TRANSPOSE  0.820000   0.000000   0.820000 (  0.826408)
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top