2011-01-30 3 views

답변

3

귀하의 답변에 감사드립니다. 그들 모두는 정말 시원한 & 계몽했다.

나는 내 자신의 대답을 내놓았다. 출력 위의 스크립트는 내 Mac에서 다음 실행

require "benchmark" 
MANY = 50000  
gifts = [ 
    "4|2323", "1", 
    "3|102343", "2", 
    "0|12330", "1", 
    "3|10234873", "2", 
    "5|2343225", "1", 
    "5|23423744", "1", 
    "2|987", "4", 
    "0|987345", "1", 
    "2|46593", "1", 
    "4|78574839", "3", 
    "3|4756848578", "1", 
    "3|273483", "3" 
] 

Benchmark.bmbm do |x| 
    x.report("each_with_index") { MANY.times { sum = 0; gifts.each_with_index { |s, i| sum += s.to_i if i % 2 == 1 }; sum } } 
    x.report("each_with_index") { MANY.times { sum = 0; gifts.each_with_index { |s, i| sum += s.to_i if i.odd? }; sum } } 
    x.report("values_at") { MANY.times { gifts.values_at(*(1..gifts.length).step(2)).inject(0) { |s, n| s += n.to_i } } } 
    x.report("each_slice") { MANY.times { gifts.each_slice(2).inject(0) { |i, (j,k)| i += k.to_i } } } 
    x.report("values_at") { MANY.times { gifts.values_at(*gifts.each_index.select { |i| i.odd? }).map(&:to_i).inject(&:+) } } 
    x.report("hash") { MANY.times { Hash[*gifts].values.map(&:to_i).reduce(:+) } } 
end 

: 내가 성능 검사를했다

sum = 0; gifts.each_with_index { |s, i| sum += s.to_i if i % 2 == 1 }; sum 

... 꽤 똑바로 앞으로의 내 대답은 같은

     user  system  total  real 
each_with_index 0.300000 0.000000 0.300000 ( 0.305377) 
each_with_index 0.340000 0.000000 0.340000 ( 0.334806) 
values_at   0.370000 0.000000 0.370000 ( 0.371520) 
each_slice  0.380000 0.000000 0.380000 ( 0.376020) 
values_at   0.540000 0.000000 0.540000 ( 0.539633) 
hash    0.560000 0.000000 0.560000 ( 0.560519) 

이 보이는 가장 빠른. 하하. Suckas! : P

2

루비 배열은 0을 기반으로하므로 홀수 색인에서 값의 합계를 계산하려고합니까? 여기

>> a = ["4|23", "1", "3|10", "2"] 
>> a.values_at(*a.each_index.select{|i| i.odd?}).map{|i| i.to_i}.inject(&:+) 
=> 3 
+0

네 말이 맞아. 내 질문을 업데이트했습니다. 감사! 쿨 솔루션! – ma11hew28

1

그것이 단계

# Your array 
ary = ["4|23", "1", "3|10", "2"] 
# the enumerator to iterate through it 
enum = (1..ary.length).step(2) 
# your scores 
scores = ary.values_at(*enum) 
# and the sum 
sum = scores.inject(0){ |s,n| s = s + n.to_i } 

차근 또한

sum = ary.values_at(*(1..ary.length).step(2)).inject(0){ |s,n| s = s + n.to_i } 
같이 쓸 수있다 :이 경우, 다음과 같은 몇 가지 필터링 ( i.odd?) 및 살균 ( i.to_i)을 수행 할
+0

왜 투표가 안되니? – edgerunner

4
["4|23", "1", "3|10", "2"].each_slice(2).inject(0) { |i, (j,k)| i += k.to_i } 
3
Hash[*a].values.map(&:to_i).reduce(:+) 
0
array = ["4|23", "1", "3|10", "2"] 

array.select.with_index {|e,i|i.odd?}.map(&:to_i).inject(:+) 
=> 3 
관련 문제