From: daz Date: 2005-10-13T21:56:56+09:00 Subject: Re: array1 + array2 newb question Robert Klemme wrote: > Kroeger, Simon (ext) wrote: > >> From: Robert Klemme [mailto:bob.news@gmx.net] > >> Since there hasn't been an #inject solution so far... :-) > > > > hmm, is the gateway broken again? > > > > a1.inject([]){|s, x| s + a2.map {|y| [x, y]}} > > > > (posted 1 hour ago) > > No, it's here. Can't tell though whether I just overlooked it > or whether the posting arrived here after I wrote mine. > > And note that your version has the disadvantage [...] A more significant disadvantage is that you both posted solutions with equivalent results but for a slightly different problem than the one posed by the OP ;) > [...] that you copy s all the time. As did my solution. > Using concat is more efficient. That's usually safe to say ... but check the b/marks. > That's why my solution just appends two element arrays to > the collecting array. :-) .... And ends up 3rd out of 3 in the b/mk race :-D > > Kind regards > > robert > After making the necessary corrections: #-------------------- require 'benchmark' include Benchmark a1 = [1,2,3] a2 = %w{a b c} BMN = 50000 # <------ ?whatever? bm(7) do |bx| bx.report('d-') { BMN.times { dz = []; a2.each{|s| dz += a1.map {|y| [y, s]}} }} bx.report('s-') { BMN.times { sk = a2.inject([]){|s,x| s + a1.map {|y| [y, x]}} }} bx.report('r-') { BMN.times { rk = a2.inject([]){|r,x| a1.each {|y| r << [y,x]}; r} }} GC.start ; GC.disable bx.report('dz') { BMN.times { dz = []; a2.each{|s| dz += a1.map {|y| [y, s]}} }} GC.start ; GC.disable bx.report('sk') { BMN.times { sk = a2.inject([]){|s,x| s + a1.map {|y| [y, x]}} }} GC.start ; GC.disable bx.report('rk') { BMN.times { rk = a2.inject([]){|r,x| a1.each {|y| r << [y,x]}; r} }} end =begin user system total real d- 5.857000 0.000000 5.857000 ( 5.880000) s- 7.145000 0.000000 7.145000 ( 7.140000) r- 8.040000 0.000000 8.040000 ( 8.070000) dz 5.415000 0.000000 5.415000 ( 5.440000) sk 6.428000 0.000000 6.428000 ( 6.420000) rk 7.353000 0.000000 7.353000 ( 7.360000) =end #-------------------- IMHO - #inject is very useful but I don't see the advantage of using it to hide an initial x = [] and subjecting it to being flung round in circles. As you can see, it doesn't gain anything, here. (Not a squabble :-) daz