eld*_*uth 1 ruby arrays iteration
我有以下代码
#!/usr/bin/ruby -w
c = 1
d = Array.new(6965) #6965 is the amount of abundant numbers below 28123 of which all numbers greater than that can be written as the sum of two abundant numbers
f = 0
while c < 28124 # no need to go beyond 28123 for this problem
a = 0
b = 1
i = true # this will be set to false if a number can be written as the sum of two abundant numbers
while b <= c/2 + 1 # checks will go until they reach just over half of a number
if c % b == 0 # checks for integer divisors
a += b # sums integer divisors
end
b += 1 # iterates to check for new divisor
end
if a > c # checks to see if sum of divisors is greater than the original number
d << c # if true it is read into an array
end
d.each{|j| # iterates through array
d.each{|k| # iterates through iterations to check all possible sums for number
# false is declared if a match is found. does ruby have and exit statement i could use here?
i = false if c - j - k == 0
}
}
c+=1 # number that we are checking is increased by one
# if a number cannot be found as the sum of two abundant number it is summed into f
f += c if i == true
end
puts f
Run Code Online (Sandbox Code Playgroud)
对于以下代码,每当我尝试对我的d
数组进行双重迭代时,我都会出现以下错误:
euler23:21:在块中(2级)来自' euler23:20:in block in'from euler23:19:in '
-': nil can't be coerced into Fixnum (TypeError)
from euler23:21:ineach'
from euler23:20:ineach'
from euler23:19:in
由于我不熟悉Ruby,我解决这个问题的各种尝试都是徒劳的.我觉得我需要包含一些库,但我的研究没有提到任何库,我不知所措.此代码用于将所有不能写入的数字相加为两个数字的总和; 这是欧拉计划的第二十三个问题.
当你这样做:
d = Array.new(6965)
Run Code Online (Sandbox Code Playgroud)
您创建一个6965 nil
值的数组.
如果在第21行之前添加了此测试代码:
p [c,j,k]
Run Code Online (Sandbox Code Playgroud)
然后你得到结果:
[1, nil, nil]
Run Code Online (Sandbox Code Playgroud)
这表明j
和k
均nil
值.您正在迭代数组中的空项.
如果您将创建更改d
为:
d = [] # an empty array, which in Ruby can change size whenever you want
Run Code Online (Sandbox Code Playgroud)
...然后你的代码运行.(我没有让它运行足够长的时间来查看它是否正确运行,但它至少在相当长的一段时间内没有错误地运行.)
最后,几点随机风格的建议:
这段代码:
while b <= c/2 + 1
if c % b == 0
a += b
end
b += 1
end
Run Code Online (Sandbox Code Playgroud)
可以更简洁地重写,更像Ruby-esque:
b.upto(c/2+1){ a+=b if c%b==0 }
Run Code Online (Sandbox Code Playgroud)
同样,这个循环:
c=1
while c < 28124
# ...
c += 1
end
Run Code Online (Sandbox Code Playgroud)
可以改写为:
1.upto(28123) do |c|
# ...
end
Run Code Online (Sandbox Code Playgroud)
当你问打破了一个循环的,你可以使用break
或next
适当,或throw
与catch
首位,而其不用于Ruby-错误处理跳转到一个特定的嵌套循环水平.