Category Archives: Ruby

Project Euler 53: Ruby

In my attempt to learn Ruby out in the open, here’s my solution for Project Euler Problem 53

I first attempted to solve this problem using the Ruby combinations libraries. That didn’t work out so well. With a second look at the problem, the provided formula ended up being just the thing to solve the problem effectively.

As always, any feedback is welcome.

# Euler 53
# http://projecteuler.net/index.php?section=problems&id=53
# There are exactly ten ways of selecting three from five,
# 12345: 123, 124, 125, 134, 135, 145, 234, 235, 245,
# and 345
# In combinatorics, we use the notation, 5C3 = 10.
# In general,
#
# nCr = n! / r!(n-r)!,where r <= n,
#              n! = n(n1)...321, and 0! = 1.
#
# It is not until n = 23, that a value exceeds
# one-million: 23C10 = 1144066.
# In general: nCr
# How many, not necessarily distinct, values of  nCr,
# for 1 <= n <= 100, are greater than one-million
timer_start = Time.now

# There's no factorial method in Ruby, I guess.
class Integer
  # http://rosettacode.org/wiki/Factorial#Ruby
  def factorial
    (1..self).reduce(1, :*)
  end
end

def combinations(n, r)
  n.factorial / (r.factorial * (n-r).factorial)
end

answer = 0

100.downto(3) do |c|
  (2).upto(c-1) { |r|
    answer += 1 if combinations(c, r) > 1_000_000
  }
end

puts answer

puts "Elapsed Time: #{(Time.now - timer_start)*1000} milliseconds"

Project Euler 52: Ruby

In my attempt to learn Ruby out in the open, here’s my solution for Project Euler Problem 52

Compared to Problem 51, this problem was a snap. Brute force and pretty quick…

As always, any feedback is welcome.

# Euler 52
# http://projecteuler.net/index.php?section=problems&id=52
# It can be seen that the number, 125874, and its double,
# 251748, contain exactly the same digits, but in a
# different order.
#
# Find the smallest positive integer, x, such that 2x, 3x,
# 4x, 5x, and 6x, contain the same digits.
timer_start = Time.now

def contains_same_digits?(n)
  value = (n*2).to_s.split(//).uniq.sort.join
  3.upto(6) do |i|
   return false if (n*i).to_s.split(//).uniq.sort.join != value
  end

  true
end

i = 100_000
answer = 0

while answer == 0
  answer = i if contains_same_digits?(i)
  i+=1
end

puts answer

puts "Elapsed Time: #{(Time.now - timer_start)*1000} milliseconds"

Project Euler 51: Ruby

In my attempt to learn Ruby out in the open, here’s my solution for Project Euler Problem 51

I know I started back up with Python this week, but I have three more Ruby solutions in the hopper and I wanted to share. For the record, Project Euler 51 was the second hardest Euler problem for me thus far. Yeah.

As always, any feedback is welcome.

# Euler 51
# http://projecteuler.net/index.php?section=problems&id=51
# By replacing the 1st digit of *3, it turns out that six
# of the nine possible values: 13, 23, 43, 53, 73, and 83,
# are all prime.
#
# By replacing the 3rd and 4th digits of 56**3 with the
# same digit, this 5-digit number is the first example
# having seven primes among the ten generated numbers,
# yielding the family: 56003, 56113, 56333, 56443,
# 56663, 56773, and 56993. Consequently 56003, being the
# first member of this family, is the smallest prime with
# this property.
#
# Find the smallest prime which, by replacing part of the
# number (not necessarily adjacent digits) with the same
# digit, is part of an eight prime value family.

timer_start = Time.now

require 'mathn'

def eight_prime_family(prime)

  0.upto(9) do |repeating_number|
    # Assume mask of 3 or more repeating numbers
    if prime.count(repeating_number.to_s) >= 3
      ctr = 1

      (repeating_number + 1).upto(9) do |replacement_number|
        family_candidate = prime.gsub(repeating_number.to_s,
          replacement_number.to_s)

        ctr += 1 if (family_candidate.to_i).prime?
      end

      return true if ctr >= 8
    end
  end

  false
end

# Wanted to loop through primes using Prime.each
# but it took too long to get to the starting value.
n = 9999
while n += 2
  next if !n.prime?
  break if eight_prime_family(n.to_s)
end

puts n
puts "Elapsed Time: #{(Time.now - timer_start)*1000} milliseconds"

Language Club – Battle of the Dynamic Languages

After dedicating the last eight weeks to learning Ruby, it’s time to move onto another language. 

I really dig Ruby.  I really enjoy its dynamism and expressiveness and always-openness and it’s been the highlight of our coding club for me so far. But that’s just my take on the language.  I know a lot of coders who’s stomachs turn with the mere thought of Ruby.  They say it’s Ruby’s openness which has them feeling uneasy.  I’d say “write a bunch of tests and get over it,” but I figure there must be more to it than always open classes and possible method collisions. Yes, there’s something else to it alright. The folks who didn’t fall head over heals for Ruby are already in love with Python. 

You might remember that Python was the first language we tackled in our coding club.  My time with Python was okay but it didn’t feel as natural to me as Ruby.  But let’s say we started with Ruby and then moved onto Python.  Would I see Python in a different light right now.  Might I even prefer Python over Ruby?  I suppose it’s possible but it’s pretty tough to test that theory – unless we visit Python for a second time.

That’s right. The language club is going to focus on Python again and in my attempt to learn Python – yet again – in the open, I’ll be posting my solutions here just as I did for Ruby.  We don’t always have second chances so I going about this relearning with two primary goals in mind: 

First, I’m going to use IronPython and the IronPython tools which provide a Python code editor, a file-based project system, and an interactive Python interpreter, all inside Visual Studio 2010.  As a note, the IronPython tools are now part of the main IronPython installer which is Version 2.7 Alpha 1 (not the latest stable version, 2.6.1) and I’d be crazy not to use them. 

Second, I’d like to make sure I’m still learning Python without a complete MS skew so I’m going to run my code through Eclipse using the PyDev plugin as well.  Heck, I might use IDLE too. I already have this setup on my machine so it’s no big deal.

Okay, that’s it for now.  I worked on the first ten Euler problems last night and the solutions will be posted shortly.

Wish me luck.

Project Euler 50: Ruby

In my attempt to learn Ruby out in the open, here’s my solution for Project Euler Problem 50

And this is Euler Problem 50. I did it — I met my goal of completely the first 50 Euler Problems in Ruby by tomorrow, August 18. This was a fun problem which I did entirely on paper, in the living room, while the rest of the family watched TV. Oh how I wish that solution “just worked” but I neglected to move the counter to 1 and establish the new sum in the outer loop. Luckily, it didn’t take long to resolve, but, again, how I wish my solution to Problem 50 “just worked” the first time.

Is there any new Ruby goodness going on here? Nope, but I was reminded of my very first Ruby error which took a while to debug the first time around:

in `+’: nil can’t be coerced into Fixnum (TypeError)

If you notice below that (s+1) evaluates to an integer which allows the upto() loop to work its magic. Remove those parenthesis and you have a completely different expression — one which throws the above error. I don’t know. I figured I’d mention it, mostly because it offered me a nice reminder of how far I’ve come.

As always, any feedback is welcome.

# Euler 50
# http://projecteuler.net/index.php?section=problems&id=50
# The prime 41, can be written as the sum of six
# consecutive primes:
#
# 41 = 2 + 3 + 5 + 7 + 11 + 13
# This is the longest sum of consecutive primes that adds
# to a prime below one-hundred.
#
# The longest sum of consecutive primes below one-thousand
# that adds to a prime, contains 21 terms, and is equal to 953.
#
# Which prime, below one-million, can be written as the sum
# of the most consecutive primes?
timer_start = Time.now

require 'mathn'

top = 1_000_000

p = []
Prime.each do |a|
  break if a > top
  p << a
end

max_consecutive = 0
upper = p.length - 1
sum, ctr, answer = 0, 0, 0

0.upto(upper) do |s|
  sum, ctr = p[s], 1

  (s+1).upto(upper) do |e|
    sum += p[e]
    break if sum > top

    ctr += 1
    next if ctr < max_consecutive

    if sum.prime? && ctr > max_consecutive
      max_consecutive, answer = ctr, sum
    end
  end
end

puts max_consecutive
puts answer
puts "Elapsed Time: #{(Time.now - timer_start)*1000} milliseconds"

Project Euler 49: Ruby

In my attempt to learn Ruby out in the open, here’s my solution for Project Euler Problem 49

Here, you will find that I took advantage of Ruby’s Prime Class and the Array.permutations method yet again. I think the solution is straight-forward and easy to read — unlike the problem description which I didn’t find very clear at all. After wrestling with the problem for a while I decided to see if 3330 was significant. Apparently, it was.

As always, any feedback is welcome.

# Euler 49
# http://projecteuler.net/index.php?section=problems&id=49
# The arithmetic sequence, 1487, 4817, 8147, in which each
# of the terms increases by 3330, is unusual in two ways:
# (i) each of the three terms are prime, and, (ii) each of
# the 4-digit numbers are permutations of one another.
#
# There are no arithmetic sequences made up of three 1-,
# 2-, or 3-digit primes, exhibiting this property, but
# there is one other 4-digit increasing sequence.
#
# What 12-digit number do you form by concatenating the
# three terms in this sequence?
timer_start = Time.now
require 'mathn'

answer = ""
Prime.each do |a|
  next if a == 1487

  b, c =  a + 3330, a + 6660
  next if !b.prime? || !c.prime?

  perms = a.to_s.chars.to_a.permutation(4).map{|p| p.join.to_i}
  next if !perms.include?(b) || !perms.include?(c)
  
  answer = a.to_s + b.to_s + c.to_s
  break
end

puts answer
puts "Elapsed Time: #{(Time.now - timer_start)*1000} milliseconds"

Project Euler 48: Ruby

In my attempt to learn Ruby out in the open, here’s my solution for Project Euler Problem 48

I challenged myself to complete the first 50 Euler Problems in Ruby by tomorrow. Having such an easy problem show up this late in the game gave me great hope that I’d meet my goal. Coming up with this solution took no time at all and unfortunately I don’t think I learned anything about Ruby over the 5 or so lines of code.

As always, any feedback is welcome.

# Euler 48
# http://projecteuler.net/index.php?section=problems&id=48
# The series, 1^1 + 2^2 + 3^3 + ... + 10^10 = 10405071317.
#
# Find the last ten digits of the series,
# 1^1 + 2^2 + 3^3 + ... + 1000^1000.
timer_start = Time.now

sum = (1..1000).reduce{ |agg, i| agg + i**i}.to_s
puts sum[sum.length - 10, 10]

puts "Elapsed Time: #{(Time.now - timer_start)*1000} milliseconds"

Project Euler 47: Ruby

In my attempt to learn Ruby out in the open, here’s my solution for Project Euler Problem 47

This solution shows off the power of built-in Ruby Array methods. You will notice Array.uniq returns a new array by removing duplicate values in self and Array.transpose, which I haven’t used prior to this solution, assumes that self is an array of arrays and transposes the rows and columns. I think the code below is a perfect example of how this method should/could be used.

As always, any feedback is welcome.

# Euler 47
# http://projecteuler.net/index.php?section=problems&id=47
# The first two consecutive numbers to have two distinct
# prime factors are:
#
# 14 = 2 x 7
# 15 = 3 x 5
#
# The first three consecutive numbers to have three
# distinct prime factors are:
#
# 644 = 2² x 7 x 23
# 645 = 3 x 5 x 43
# 646 = 2 x 17 x 19.
#
# Find the first four consecutive integers to have four
# distinct primes factors. What is the first of these numbers?
timer_start = Time.now

require 'mathn'

distinct_factors, consecutive_integers = 4, 4
counter, answer, i = 0, 0, 1

while counter < consecutive_integers
  primes, powers = i.prime_division.transpose
  
  if (primes != nil && primes.uniq.length >= distinct_factors)
    counter += 1
    answer = i if counter == 1
  else
    counter, answer = 0, 0
  end

  i += 1
end

puts answer
puts "Elapsed Time: #{(Time.now - timer_start)*1000} milliseconds"