2017-01-27 86 views
-2

我試圖從兩個單獨的陣列總結2個數組元素的值從結尾到開頭,以查看是否該總和大於9.試圖從兩個不同的陣列

我有求和陣列元素值測試我的代碼和不工作的部分是。

if halfa[i] + halfb[i] > 9 

有沒有人知道我要去哪裏錯了?任何幫助將非常感激。

text = gets.chomp 


    half1 = text.slice(0,10) 
    half2 = text.slice(text.length - 10,text.length) 
    puts half1 
    puts half2 

    halfa = half1.split("") 
    halfb = half2.split("") 

    halfa.map! { |i| i.to_i } 
    halfb.map! { |i| i.to_i } 

    count = 0 

     for i in halfa.length.downto(0) 
      if halfa[i] + halfb[i] > 9 
       count += 1 
      end 
     end 

    print count 
+1

什麼'text'看起來像? –

+0

每個數組應該有多少個數字,導致text.slice(0,10)會給出11個字符而不是11個數字 –

+0

@TravisSmith你錯了。 'String#slice'的第二個參數是一個長度,而不是索引。 https://repl.it/FXp3 –

回答

1

for i in halfa.length.downto(0):halfa.length爲10,但是陣列具有從零開始指數:從0開始halfa[10]不存在計數。

for i in (halfa.length-1).downto(0)會導致 - 至少有一些東西。

0

for循環會在halfa.length啓動,這是10在halfa指數最高爲9,所以halfa[10]回報nil

您可以通過將halfa.length更改爲(halfa.length - 1)來解決此問題,但您仍然可以使用一些非單一代碼。在Ruby中很難看到for,因爲總是有更好的選擇。例如:

text = "31415926535897932384" 

half_size = text.size/2 

count = half_size.times.count do |i| 
    text[i].to_i + text[i+half_size].to_i > 9 
end 

puts count 
# => 4 

上面的代碼假定文本將具有偶數個字符。如果您願意,您也可以將half_size硬編碼爲10。

Integer#times方法將通過其接收器枚舉數字0,例如, 5.times.to_a返回[0, 1, 2, 3, 4]Array#count方法返回塊產生真值的次數。

看到它在repl.it:https://repl.it/FXpa

2

你有一個差一錯誤在這裏,經典的編程錯誤,你開始迭代在i是數組的長度,但halfa[5]nil,數組從0到4.

這裏的問題是您使用笨重的for循環方法進行迭代。紅寶石,不像幾乎所有其他語言,迴避是贊成使用迭代方法:

halfa.each_index do |i| 
    if halfa[i] + halfb[i] > 9 
    count += 1 
    end 
end 

這就是你有什麼最直譯。請注意,您可以清理你的代碼很大,如果它在一個更紅寶石般的符號所表達的:

text = "4443466664" 

# Define a variable here that represents the slice size to use 
slice_size = 5 

# Cut this into groups of 5 characters, convert each chunk by remapping 
# the values to integers, then save it all into one variable. 
halves = text.chars.each_slice(slice_size).map { |a| a.map(&:to_i) } 

# The result looks like this: 
# => [[4, 4, 4, 3, 4], [6, 6, 6, 6, 4]] 

# Count all pairs that add up to more than 9 using count with a block 
# that defines when to count them. Note the use of ... which goes up to 
# but does not include the upper bound. 
count = (0...slice_size).count do |i| 
    halves[0][i] + halves[1][i] > 9 
end 

# => 3 
2

一種方式重構你的代碼將與Array#zipEnumerable#count

text = "123456789098765" 
n  = 10 

digits = text.chars.map(&:to_i) 
# [1, 2, 3, 4, 5, 6, 7, 8, 9, 0, 9, 8, 7, 6, 5] 

first = digits.first(n) 
# [1, 2, 3, 4, 5, 6, 7, 8, 9, 0] 
last = digits.last(n) 
# [6, 7, 8, 9, 0, 9, 8, 7, 6, 5] 
pairs = first.zip(last) 
# [[1, 6], [2, 7], [3, 8], [4, 9], [5, 0], [6, 9], [7, 8], [8, 7], [9, 6], [0, 5]] 

count = pairs.count{ |a, b| a + b > 9 } 
# 6