Array partition sums
I have an array of xs
numbers and I need to calculate the sums of the elements in three consecutive sections in it. sections xs[0]
, xs[1, N]
and xs[N + 1, N]
for some integer N
. For example, for N = 2
:
[1, 2, 3, 4, 5] #=> 1, 5, 9
my implementation is below. I couldn't make it more efficient in terms of memory / speed, but it still worries me, I guess I have nothing to do now, but maybe there is a more elegant and concise way to do it? I don't need to create an array, it can be any other structure.
xs.each_with_index.reduce([0, 0, 0]) do |m, x|
v, i = x
j = (i > N ? 2
: i > 0 ? 1
: 0)
m[j] += v.to_i
m
end
source to share
[xs[0..0],xs[1..N],xs[N+1..-1]].map{|x|x.reduce{|a,b|a+b}}
a.rb
:
N = (rand * 1E6).to_i xs = 1.upto(1E6).to_a xs.each_with_index.reduce([0, 0, 0]) do |m, x| v, i = x j = (i > N ? 2 : i > 0 ? 1 : 0) m[j] += v.to_i m end
b.rb
:
N = (rand * 1E6).to_i xs = 1.upto(1E6).to_a [xs[0..0],xs[1..N],xs[N+1..-1]].map{|x|x.reduce{|a,b|a+b}}
Time:
$ time ruby a.rb
ruby a.rb 0.85s user 0.01s system 99% cpu 0.860 total
$ time ruby b.rb
ruby b.rb 0.29s user 0.01s system 99% cpu 0.296 total
Ruby version:
$ ruby -v
ruby 1.9.3p194 (2012-04-20 revision 35410) [x86_64-darwin12.0.0]
source to share