views:

153

answers:

3

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?

A: 

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.

RyanJM
+2  A: 

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) 
lambdabutz
Reading through your code again, it's clear you know most of these methods already, apologies for not reading it thoroughly enough. In the case of refactoring, you are a little proc heavy, but as ryanjm.mp said, this is a matter of style, though I don't think you'll find many ruby people who agree with your style. Certain things like storing your triangle_number lambda to a variable is unnecessary if you are only using it once. factor_count would also make more sense as a method than a lambda, in terms of readability and even exposing it later. Good luck.
lambdabutz
i got too carried away with lambdas, since its a new thing for me :) to be honest i never programmed in any language that supports functional programming paradigm, thanks for the advice
RaouL
+4  A: 

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?
        # ...
    
Marc-André Lafortune