Showing posts with label tutorial. Show all posts
Showing posts with label tutorial. Show all posts

Thursday, August 11, 2011

Ruby Tutorials

Over the last few weeks I have found quite a few places that have been helpful in learning about Ruby, I wanted to make a comprehensive list here for any that come after.  Digging through Google can be tedious sometimes. 

Ruby Essentials

Mr. Neighborly's Humble Little Ruby book

Tutorials Point

Project Euler #4 in Ruby

Project Euler #4

A palindromic number reads the same both ways. The largest palindrome made from the product of two 2-digit numbers is 9009 = 91 × 99.  Find the largest palindrome made from the product of two 3-digit numbers.

Another great example here! 


  1. success = 0
  2. for i in (100..999)
  3.   for j in (100..999)
  4.     k = i * j
  5.     if (k.to_s == k.to_s.reverse && k > success)
  6.       success = k
  7.     end
  8.   end
  9. end
  10. puts success

What happens here is very straightforward, because he is asking for two, three-digit numbers multiplied together, it immediately tells us the constraints of our two for loops, and thereby the maximum possible value we could have:  999x999 or 998001.  What we need to do then is just compare the value we get from multiplying them together, and then the reverse of that, thereby checking to see if it is palindromic.  It's super easy in Ruby as well, you just have to convert both to strings using the '.to_s' operator and then the '.reverse' on one of them.  In line 5 the first conditional 'k.to_s == k.to_s.reverse' checks to see if it is palindromic and the second if it is greater than the last palindrome that we found, because there will be many.  If it is, the line 6 states that we save it. 

This code runs in just over a second for me, satisfying the 1 minute guideline set forth by the project Euler team. 

Project Euler #2 in Ruby

Project Euler #2

Each new term in the Fibonacci sequence is generated by adding the previous two terms. By starting with 1 and 2, the first 10 terms will be:
1, 2, 3, 5, 8, 13, 21, 34, 55, 89, ...
By considering the terms in the Fibonacci sequence whose values do not exceed four million, find the sum of the even-valued terms.

Here is my solution:

  1. one = 1
  2. two = 1
  3. sum = 0
  4. while (two <= 4_000_000)
  5.   temp = one
  6.   one = two
  7.   two = one + temp
  8.   if (two % 2 == 0)
  9.     sum += two
  10.   end
  11. end
  12. puts sum

You will notice the '_' symbol where the commas would be (or periods if you don't live in the States), for reference in keeping track of how many zeroes we have if we were writing '4,000,000' out by hand.  Coding up '4_000_000', is basically the same, the compiler will ignore the underscores.  It is just so we can keep track of how many zeroes there are. 

I wanted to illustrate something handy in this tutorial, called 'parallel assignment'.  Nothing earth shattering, but it could cut down on the number of times you have to press the enter and equals key.

Ruby allows you to assign variables to values, lined up one after the other, on a single line of code.  If you will notice we combined lines 1 through 3 above into a single line (1) below.  The same is true for lines 5 and 6 above into a single line 3 below.  Line 4 below is still on its own line as Ruby won't let you do arithmetic while doing parallel assignment. 

  1. one, two, sum = 1, 1, 0
  2. while (two <= 4_000_000)
  3.   temp, one = one, two
  4.   two = one + temp
  5.   if (two % 2 == 0)
  6.     sum += two
  7.   end
  8. end
  9. puts sum

This isn't the most clever way of solving this problem, but certainly the easiest to understand.  We simply do what the question asks for:  Add up each even term of the Fibonacci sequence below 4,000,000. 

Wednesday, August 10, 2011

Project Euler #1 in Ruby

Project Euler #1


If we list all the natural numbers below 10 that are multiples of 3 or 5, we get 3, 5, 6 and 9. The sum of these multiples is 23.

Find the sum of all the multiples of 3 or 5 below 1000.

The problem is fairly straightforward, and is the most correctly answered problem in the whole set.  I will be explaining a little bit of Ruby in this solution I give.

  1. x = 0
  2. sum = 0
  3. while (x < 1000)
  4.   if (x % 3 == 0 && x % 5 == 0)
  5.     sum += x
  6.   elsif (x % 3 == 0)
  7.     sum += x
  8.   elsif (x % 5 == 0)
  9.     sum += x
  10.   end
  11.   x += 1
  12. end
  13. puts sum

1.  This is the declaration of a variable in Ruby, and you will notice you do not have to declare its type.  It is inferred from what the variable is set equal to when it is declared.  Handy!  This is what is meant by being a "dynamically typed language", other programming languages like C require you to declare the variable's type at declaration and forever afterward it is of that type.  This is referred to as a "statically typed language". 

2.  See line 1.

3.  While loops in Ruby are very similar to those seen in Java or C++, the difference being we don't use brackets, instead we get a great deal of use out of 'end' statements.  You will notice that everything within the while loop is tabbed out once (at least).  If you use NetBeans, or Notepad++, or some such fancy editor, it will automatically do this and help you see where your blocks of code are located.

What you need to know for 'while' loops, is that you need the keyword 'while' then a conditional, and to close the 'while' block, you must include the 'end' keyword, just like I did on line 12. 

For more information on while loops in Ruby, you may use Tutorials Point, or the slightly more concise Techotopia wiki.

4.  This is our first look at 'if' statements.  Again, very similar to C++, even in the modifiers '&&' or '||' which are 'AND' and 'OR' respectively, in how they modify logical statements. 

In our case, line 4 says "if x modulus 3 is equal to 0 and if x modulus 5 is equal to 0 then...", and that is all there is to it!  For those new to the game, modulus is just looking for the remainder after we divide.

For example:  6 % 5 = 1, because 6/5 = 1 R 1, where 'R' stands for 'remainder', and % stands for 'modulus' or 'mod' for short.

If you would like to learn more about the modulus, or the area of modular arithmetic in mathematics, you can look here, for a quick primer on the subject.

5.  Line 5 is just what it looks like for anyone that has used C or Java, the "+=" operator takes the left hand side and simply adds to it the right hand side.  For example:

  1. x = 0   #=> 0
  2. x += 3  #=> 3
  3. x += 39 #=> 42

6.  An 'elsif' statement is just an "else" and "if" statement crammed together, and takes a conditional just like the 'if' statement in line 4.

10.  We will skip to line 10, as lines 7 through 9 are explained previously.  All there is to explain here is that when using 'if', you must also close the block with the 'end' keyword.  This is not true for an 'else' or 'elsif' as these are part of a larger 'if' block or statement.

13.  This is the last line in our code, and important if we want to know what the answer is!  "puts" stands for "put string", and all you have to do to use it is put a string after it.  Our sum happens to be of the 'Integer' class, but it has been written in such a way to know what to do when we use it in the 'puts' statement.  More on this later!



As for what we are trying to accomplish in this project Euler problem, we want to sum up all of the multiples of 3 and 5 below 1000.  Pretty straightforward.  There are a few places where one can trip up though:

1.  If you incorrectly sum up multiples of both 3 and 5.  For example, 15 is a multiple of both 3 and 5, and if you write your code incorrectly you will get a sum that is too large, because you have added twice every multiple of both 3 and 15.

2.  Another place is not noticing that the question states below 1000, not up to and including 1000.  So just be wary of that. 

If anyone has some other pitfalls to be wary of, please email me and I will be sure to include them here, for those that follow after!  Good luck all, and happy coding!