2014-10-06 22 views
-2

是否有一種方法不需要.each,可以優雅地添加所有的奇數/偶數索引數字。紅寶石優雅的方式來添加一個數字的所有偶數或奇數索引的數字?

eg. 872653627 

Odd: 7 + 6 + 3 + 2 = 18 
Even: 8 + 2 + 5 + 6 + 7 = 28 
+5

如果你寫的話會有一個。那麼爲什麼不從一些代碼開始呢? – 2014-10-06 09:04:35

+0

那麼我打算使用一個'.each','counter',一個帶有mod的if語句和'用於保存偶數和偶數的兩個變量。一段真正可恥的代碼。 – surfer190 2014-10-06 09:10:44

+0

@StevieG現在你正在尋找一種沒有'each',counter,'if'語句,模和變量的方法嗎? – Stefan 2014-10-06 11:45:03

回答

6
number.to_s.chars.map(&:to_i).    # turn string into individual numbers 
    partition.with_index { |_, i| i.odd? }. # separate the numbers into 2 arrays 
    map { |a| a.reduce(:+) }     # sum each array 
#=> [18, 28] 
+0

恕我直言優雅的意思是「可讀性強,易於理解,隱藏其複雜性」。這涵蓋了所有三個! – microspino 2014-10-17 09:54:00

2
number = 872653627 

result = number.to_s.chars.map(&:to_i).group_by.with_index {|_, i| i.odd? }.map {|k,v| [k,v.inject(0, :+)]}.to_h 

odd = result[true] 
even = result[false] 
+0

不知道'chars',thx :) – 2014-10-06 09:11:15

+0

我覺得'partition'在這裏比'group_by'好:-) – 2014-10-06 09:23:17

3
num=872653627 

num.to_s.split(""). 
    select.each_with_index { |str, i| i.odd? }. 
    map(&:to_i).reduce(:+) 

和類似地用i.even?

+0

他問沒有'each',我覺得我在這裏看到一個'each'。 – pguardiario 2014-10-06 10:16:47

1
num=872653627 
odd = even = 0 
num.to_s.split(""). 
    each_with_index { |data, index| index.odd? ? odd += data.to_i : even += data.to_i } 

odd #=> 18 
even #=> 28 
0

如何:

num = '872653627' 
[/.(\d)/,/(\d).?/].map{|re| num.scan(re)}.map{|x| x.flatten.map(&:to_i).reduce(:+)} 
#=> [18, 28] 
1
x, odd, even, alt = 872653627, 0, 0, false 
until x.zero? 
    x, r = x.divmod(10) 
    alt ? odd += r : even += r 
    alt ^= true 
end 

odd #=> 18 
even #=> 28 
1

這是一個很大的問題!

無論如何,解決方案非常簡單。

string = "872653627" 

即使索引位數

string.chars.select.with_index{|e,i|i.even?}.map(&:to_i).reduce(:+) 

對於奇數索引位數

string.chars.select.with_index{|e,i|i.odd?}.map(&:to_i).reduce(:+) 

希望這有助於。

1

如果允許each_slice的方法,將數字轉換爲數組,那麼slice將是簡潔的。

num = 872653627.to_s.split(//).map{|x| x.to_i}.reverse 
even= num.each_slice(2).inject(0){|total , obj| total + obj[0]} 
odd = num.each_slice(2).inject(0){|total , obj| total + obj[1]} 

我困惑的奇/偶索引這裏位數的定義,請隨時改變obj的[0],OBJ [1]和.reverse適合的奇/偶索引位不同的定義。

相關問題