ruby - 遍历数组(欧拉计划 #23)

标签 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

对于以下代码,每当我尝试为我的 d 进行双重迭代时数组,我想出了以下错误:

euler23:21:in -': nil can't be coerced into Fixnum (TypeError)<br/> from euler23:21:inblock (2 levels) in '
from euler23:20:in each'<br/> from euler23:20:inblock in '
from euler23:19:in each'<br/> from euler23:19:in'

由于我不熟悉 Ruby,所以我尝试解决此问题的各种尝试都没有成功。我感觉我需要包含一些库,但我的研究没有提到任何库,我很茫然。这段代码的目的是求和所有不能写成两个丰富数字之和的数字;它是 twenty third question from Project Euler .

最佳答案

当你这样做时:

d = Array.new(6965)

您创建了一个包含 6965 个 nil 值的数组。

如果在第 21 行之前添加此测试代码:

p [c,j,k]

然后你得到结果:

[1, nil, nil]

这表明 jk 都是 nil 值。您正在遍历数组中的空项。

如果您将 d 的创建更改为:

d = [] # an empty array, which in Ruby can change size whenever you want

...然后您的代码运行。 (我没有让它运行足够长的时间来查看它是否运行正确,但它至少在相当长的一段时间内没有错误地运行。)


最后,一些随意的风格建议:

这段代码:

while b <= c/2 + 1
  if c % b == 0
    a += b
  end
  b += 1
end

可以更简洁、更像 Ruby 的方式重写为:

b.upto(c/2+1){ a+=b if c%b==0 }

同样,这个循环:

c=1
while c < 28124
  # ...
  c += 1
end

可以重写为:

1.upto(28123) do |c|
  # ...
end

当你询问是否打破循环时,你可以使用break or next视情况而定,或 throw and catch ——在 Ruby 中不用于错误处理——跳转到特定的嵌套循环级别。

关于ruby - 遍历数组(欧拉计划 #23),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15769265/

相关文章:

javascript - 将变量插入数组返回未定义

c - 汉诺塔的实现——迭代过程

ruby - Rails 3.2 遍历数组

loops - 遍历 Capybara 中的项目

jQuery Chosen 插件动态添加选项而不使用 Ajax?

JavaScript循环从数组中随机选择

c# - 为什么我的 Interop 代码会抛出 "Stack cookie instrumentation code detected a stack-based buffer overrun"异常?

c++ - 尝试使用 SWIG 将 C++ 编译为 Ruby 时没有这样的文件或目录 "ruby/config.h"

javascript - 我正在尝试添加评论而不刷新页面

ruby-on-rails - 将业务规则移动到模型中