更多类似 Ruby 的解决方案来解决这个问题吗?

发布于 2024-09-05 11:47:29 字数 758 浏览 13 评论 0原文

我正在学习 ruby​​ 并通过解决 Project Euler 中的问题来练习它。

这是我针对问题 12 的解决方案。

# Project Euler problem: 12
# What is the value of the first triangle number to have over five hundred divisors?

require 'prime'

triangle_number = ->(num){ (num *(num + 1)) / 2 }

factor_count = ->(num) do
  prime_fac = Prime.prime_division(num)
  exponents = prime_fac.collect { |item| item.last + 1 }
  fac_count = exponents.inject(:*)
end

n = 2
loop do
  tn = triangle_number.(n)
  if factor_count.(tn) >= 500
    puts tn
    break
  end
  n += 1
end

这段代码有什么可以改进的地方吗?

I am learning ruby and practicing it by solving problems from Project Euler.

This is my solution for problem 12.

# Project Euler problem: 12
# What is the value of the first triangle number to have over five hundred divisors?

require 'prime'

triangle_number = ->(num){ (num *(num + 1)) / 2 }

factor_count = ->(num) do
  prime_fac = Prime.prime_division(num)
  exponents = prime_fac.collect { |item| item.last + 1 }
  fac_count = exponents.inject(:*)
end

n = 2
loop do
  tn = triangle_number.(n)
  if factor_count.(tn) >= 500
    puts tn
    break
  end
  n += 1
end

Any improvements that can be made to this piece of code?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

丿*梦醉红颜 2024-09-12 11:47:29

正如其他人所说,Rubyists 使用方法或块的方式比 lambda 多。

Ruby 的 Enumerable 是一个非常强大的 mixin,所以我觉得在这里以与 Prime 类似的方式构建一个可枚举是值得的。所以:

require 'prime'
class Triangular
  class << self
    include Enumerable
    def each
      sum = 0
      1.upto(Float::INFINITY) do |i|
        yield sum += i
      end
    end
  end
end

这是非常通用的。只是检查它是否有效:

Triangular.first(4) # => [1, 3, 7, 10]

很好。现在您可以使用它来解决您的问题:

def factor_count(num)
  prime_fac = Prime.prime_division(num)
  exponents = prime_fac.collect { |item| item.last + 1 }
  exponents.inject(1, :*)
end

Triangular.find{|t| factor_count(t) >= 500}  # => 76576500

注释

  • Float::INFINITY 是 1.9.2 中的新增功能。使用 1.0/0require 'backports' 或执行循环(如果使用早期版本)。
  • 可以通过首先检查块是否通过来改进each;你会经常看到这样的东西:

     def 每个
        返回_enum __method__除非block_given?
        # ...
    

As others have stated, Rubyists will use methods or blocks way more than lambdas.

Ruby's Enumerable is a very powerful mixin, so I feel it pays here to build an enumerable in a similar way as Prime. So:

require 'prime'
class Triangular
  class << self
    include Enumerable
    def each
      sum = 0
      1.upto(Float::INFINITY) do |i|
        yield sum += i
      end
    end
  end
end

This is very versatile. Just checking it works:

Triangular.first(4) # => [1, 3, 7, 10]

Good. Now you can use it to solve your problem:

def factor_count(num)
  prime_fac = Prime.prime_division(num)
  exponents = prime_fac.collect { |item| item.last + 1 }
  exponents.inject(1, :*)
end

Triangular.find{|t| factor_count(t) >= 500}  # => 76576500

Notes:

  • Float::INFINITY is new to 1.9.2. Either use 1.0/0, require 'backports' or do a loop if using an earlier version.
  • The each could be improved by first checking that a block is passed; you'll often see things like:

      def each
        return to_enum __method__ unless block_given?
        # ...
    
爱的十字路口 2024-09-12 11:47:29

与其一次性解决问题,不如查看问题的各个部分可能会帮助您更好地理解 ruby​​。

第一部分是找出三角形的编号是多少。由于这使用自然数序列,因此您可以使用 ruby​​ 中的范围来表示它。下面是一个例子:

(1..10).to_a => [1,2,3,4,5,6,7,8,9,10]

ruby 中的数组被认为是可枚举的,并且 ruby​​ 提供了很多方法来枚举数据。使用这个概念,您可以使用each 方法迭代这个数组,并传递一个对数字求和的块。

sum = 0
(1..10).each do |x|
  sum += x
end

sum => 55

这也可以使用另一种称为注入的可枚举方法来完成,该方法将从前一个元素返回的内容传递到当前元素。使用这个,你可以在一行中得到总和。在此示例中,我使用 1.upto(10),其功能与 (1..10) 相同。

1.upto(10).inject(0) {|sum, x| sum + x} => 55

逐步执行此操作,第一次调用时,sum = 0,x = 1,因此 (sum + x) = 1。然后将其传递给下一个元素,因此 sum = 1,x = 2,(sum + x) ) = 3. 接下来 sum = 3, x = 3, (sum + x) = 6. sum = 6, x = 4, (sum + x) = 10. 等等,

这只是这个问题的第一步。如果你想以这种方式学习语言,你应该解决问题的每个部分,并学习适合该部分的知识,而不是解决整个问题。

重构的解决方案(虽然效率很低)

def factors(n)
  (1..n).select{|x| n % x == 0}
end

def triangle(n)
  (n * (n + 1)) / 2
end

n = 2

until factors(triangle(n)).size >= 500
  puts n
  n += 1
end

puts triangle(n) 

Rather than solve the problem in one go, looking at the individual parts of the problem might help you understand ruby a bit better.

The first part is finding out what the triangle number would be. Since this uses sequence of natural numbers, you can represent this using a range in ruby. Here's an example:

(1..10).to_a => [1,2,3,4,5,6,7,8,9,10]

An array in ruby is considered an enumerable, and ruby provides lots of ways to enumerate over data. Using this notion you can iterate over this array using the each method and pass a block that sums the numbers.

sum = 0
(1..10).each do |x|
  sum += x
end

sum => 55

This can also be done using another enumerable method known as inject that will pass what is returned from the previous element to the current element. Using this, you can get the sum in one line. In this example I use 1.upto(10), which will functionally work the same as (1..10).

1.upto(10).inject(0) {|sum, x| sum + x} => 55

Stepping through this, the first time this is called, sum = 0, x = 1, so (sum + x) = 1. Then it passes this to the next element and so sum = 1, x = 2, (sum + x) = 3. Next sum = 3, x = 3, (sum + x) = 6. sum = 6, x = 4, (sum + x) = 10. Etc etc.

That's just the first step of this problem. If you want to learn the language in this way, you should approach each part of the problem and learn what is appropriate to learn for that part, rather than tackling the entire problem.

REFACTORED SOLUTION (though not efficient at all)

def factors(n)
  (1..n).select{|x| n % x == 0}
end

def triangle(n)
  (n * (n + 1)) / 2
end

n = 2

until factors(triangle(n)).size >= 500
  puts n
  n += 1
end

puts triangle(n) 
天邊彩虹 2024-09-12 11:47:29

看起来您刚刚编写过 Ocaml 或其他函数式语言。在 Ruby 中,您可能需要使用更多 def 来定义您的方法。 Ruby 致力于保持清洁。但这也可能是个人偏好。

您可以使用 while (faction_count(traingle_number(n)) < 500) do 来代替 loop do,但对于某些人来说,一行可能太多了。

It looks like you are coming from writing Ocaml, or another functional language. In Ruby, you would want to use more def to define your methods. Ruby is about staying clean. But that might also be a personal preference.

And rather than a loop do you could while (faction_count(traingle_number(n)) < 500) do but for some that might be too much for one line.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文