Perpetually In Beta.

Archive for the ‘Ruby’ tag

Project Euler - Problem 4 - Palindromes

with one comment

Project Euler “is a series of challenging mathematical/computer programming problems that will require more than just mathematical insights to solve. Although mathematics will help you arrive at elegant and efficient methods, the use of a computer and programming skills will be required to solve most problems.”

I've been working through some of the projects on the website to help teach myself Ruby in my space time.

Problem 4 of Project Euler states the following:

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.

Just doing some simple calculations, the smallest number that can be generated by two 3 digits numbers multiplied together is:

100 * 100 = 10,000 which is a five digit number.  
An example of a five digit palindrome is 10101

The largest number is:

999 x 999 = 998,001 which is a six digit numbers.
An example of a six digit palindrome is 101101.

With this information in mind, the solution I came up with in Ruby is below.

class Palendromes
 
  def initialize
    @Solutions = []
  end
 
def FindPalendromes
 
  for x in 100..999
    for y in 100..999
 
      a = x * y
      a = a.to_s
      next if(a.length % 2 != 0)  
 
      b = []
      a.scan(/[0-9]/) do |z|
        b << z
      end
 
     @Solutions << a if(isPalendome?(b)) 
 
    end
  end
 
  @Solutions.sort
 
end
 
def isPalendome?(array)
 
  reversearray = array.reverse
  for x in 0..array.length
    return false if array[x] != reversearray[x]
  end
 
  return true
 
end
 
end
 
a = Palendromes.new
solutions = a.FindPalendromes
puts solutions

Starting at the bottom, a is set equal to a new instance of class Palindromes which is initialized with a call to the new method which in turn calls the initialize method which declares a new array called 'Solutions' where all the possible palindromes will be stored.  To find the palindromes, the 'FindPalindromes' method is deployed.  

FindPalindromes creates two loops from 100 to 999 so that every product of two three digit combination of numbers will be checked.  Entering the double for loop, x and y are multiplied together and stored in 'a'.  'a' is converted to a string so it can be more easily manipulated and it's length is checked.  If a is a five digit number and not a six digit number, a is discarded because it is obviously not the 'largest palindrome.'  

Next, using Regular Expressions,  each individual number is extracted from a (which is one long string) and put in individual elements in an newly created array b.  

For example the following conversion is made if a is equal to the string  '123456.'

b = {1, 2, 3, 4, 5, 6} 

This is done so that array functions can be used to check if the number is actually a palindrome.  

Next, b is sent to the method isPalindrome() which checks if the numbers contained in b are of a palindromic nature.  The isPalindrome() method is simple.  The method reverses b and stores the results in 'reversearray,' then, it loops through the length of the array comparing each element.  If an element doesn't match up, it returns false and nothing happens.  If however, every element matches, the isPalindrome method returns true and a is pushed into the Solutions array.

When the double for loop has exhausted every possible triple digit product combination, the solution array is sorted and returned to be printed to the screen.  

The answer is: 906609

My solution, while yielding the correct answer, is not the most elegant solution I discovered (not to my surprise as I am still learning the intricacies of the Ruby Programming language).  On the Project Euler forum, Olathe posted the following code:

max = 0
100.upto(999) { |a|
  a.upto(999) { |b|
    prod = a * b
    max = [max, prod].max if prod.to_s == prod.to_s.reverse
  }
}
puts "Maximum palindrome is #{ max }."

This code is sick (in a good way). He creates two for loops, finds the product of two three digit numbers, and converts the answer to a string — which is what I did in my code, but this is where the similarities end. Instead of extracting single digits into an array, he simply compares the product string to a reversed product string. If they match (if the number is a palindrome), he compares the number to the previous maximum number stored in the 'max' variable. If bigger then the previous max, he stores the number in match. If less, he discards it. Yes. Very Nice.

Written by codingwithoutcomments

September 9th, 2008 at 10:12 pm

Posted in Project Euler

Tagged with , ,

Blogging Shoes - The Simple-Calc Application

without comments

shoooes!

shoooes!

Shooooes is a cross-platform magical GUI library for Ruby created by the notorious whytheluckystiff author of Why’s Poinant Guide to Ruby and Try Ruby! (in your browser).

Today we are going to be looking at the Simple-Calc Application.  If you don't already have the code, you can download it here.

Overview

The simple-calculator is not just a catchy name.  It is what is says, that is, it IS a simple calculator.  Hit 7, press plus, hit 7 again, press equals yields you 14 in the upper right hand corner.  Nothing out of the ordinary.  However, look under the hood and there's a lot of interesting craftsmanship.

Simple-Calc.rb

Simple-Calc.rb

The entire application is composed of one class (Calc), two stacks, and two flows.  The application itself is a flow (this is a given), but a stack is added to the original flow.  To this stack, another stack is added for the displayed value (seen as '0′ in the picture above), and each button is added to a flow.

flow :width => 218, :margin => 4 do
      %w(7 8 9 / 4 5 6 * 1 2 3 - 0 Clr = +).each do |btn|
        button btn, :width => 46, :height => 46 do
          method = case btn
            when /[0-9]/: 'press_'+btn
            when 'Clr': 'press_clear'
            when '=': 'press_equals'
            when '+': 'press_add'
            when '-': 'press_sub'
            when '*': 'press_times'
            when '/': 'press_div'
          end
 
          number.send(method)
          number_field.replace strong(number)
        end
      end

The code to create the buttons in the flow is interesting.  Each button, 7 through +, is dynamically created and added to the flow with a height and width of 46.  When a button is pressed, the case statement evaluates which button was pressed and returns the name of that button (press_nameOfButton) in string form to the method variable.  This method variable (in string form) is then passed to the single instance of the Calc class (entiteld 'number') with the method send().

The send() method

When I first looked at this code, I was confused because I couldn't find the send method anywhere in the Calc class.  I did a little research and discovered that the send() method is a general-purpose method that can be used on any Class or Object in Ruby.  If not overridden, send() accepts a string and calls the name of the method whose string it is passed.  For example, if the user clicks the "Clr" button, the 'press_clear' string will be sent to the send() method and the 'press_clear' method in the Calc class will be called.  The send() method allows for a fun and dynamic way to call functions in Ruby.

The define_method command

Not only did I not see the 'send' method, I also didn't see any other of the following methods: "press_1″ through "press_9″ as well as "press_add", "press_sub", "press_times, and "press_div."  My only clue was the following code:

((0..9).each do |n|
    define_method "press_#{n}" do
      @number = @number.to_i * 10 + n
    end
  end

The above code uses the 'define_method' command to dynamically create the methods "press_1″ through "press_9."  Rather then typing all 10 methods which essentially contain the same code, the define_method command is used to generate these methods on the fly as needed.  The same is done with the methods add through divide.

{'add' => '+', 'sub' => '-', 'times' => '*', 'div' => '/'}.each do |meth, op|
    define_method "press_#{meth}" do
      @op = op
      @previous, @number = @number, nil
    end
  end

The final calculation

Once the big mysteries of the program were figured out, the rest was relatively straight foward.  The first number pressed gets saved into @previous, the operation (+ - / * ) gets saved into @op, and the second number gets saved into @number.  Then, when '=' is pressed the 'press_equals' method is invoked.

def press_equals
    @number = @previous.send(@op, @number.to_i)
    @op = nil
  end

Again, the sly send method is used.  This time, however, it is called on an integer @previous.  The integer class has an overriden send() method that takes both an operator and another number, adds, subtracts, multiplies, or divides the numbers together, and returns the result.  The result is stored as @number which can then be retrieved by a call to the to_s method and displayed on the screen.

 def to_s
    @number.to_s
  end

Conclusion

whytheluckystiff continues to astound me with the bredth of his knowlege of Ruby and his astounding code craftmanship.  The simple calculator, while simple, demonstrates in just a few lines of code what makes Ruby and Shoes so magical and special.

Written by codingwithoutcomments

September 1st, 2008 at 2:13 pm

Til Death Due Us Part - Project Euler - Problem 3

without comments

Project Euler "is a series of challenging mathematical/computer programming problems that will require more than just mathematical insights to solve. Although mathematics will help you arrive at elegant and efficient methods, the use of a computer and programming skills will be required to solve most problems."

Lot's of programmers recently have been using Project Euler as a form of 'Code Kata:'  a philosophy that believes that greatness comes through diligent practicing.  Steve Yegge written on the subject as well as Kathy Sierra.  The idea is that you can be insanely great at anything if you practice at it.  Sure, some people are natural geniuses — and you will never be better then them.  But if you want to, you can be in the top 1% of learned people on any particular subject.

I'm not sure if I believe them, but heck, i think that the idea inspires lots of mediocre programmers ( like myself ) to wake up each day and learn new stuff.  And that in itself is worth something, right?  I do believe that if you just set aside one hour per day to learn something new, you can become quite proficient in anything at all in a shorter period of time then you even imagined.  Most people have a hard time with this though.  They have a seeing that just one hour per day can lead to incredible results.  I myself was in this category until I learned the 'Til Death Due Us Part' productivity method.  On my Google homepage, I have the following widget on display:

The 'Countdown' widget shows me the (estimated) number of days I have until I die.  Instead of brimming over with horrible sadness everyday, the huge number of days I have left actually motivates me.  I just think about this simple fomula:

Number of Hours Per Day * Number of Days Til Death = Total Number of Hours

If I started today learning Ruby and practiced Ruby one hour per day, by the end of my life I will have practiced Ruby 17,193 hours.  What are you NOT going to be good at after practicing for that long?  With that in mind, you have no excuses.  It is never too late for you to learn anything… well, provided you are not already 83 years old.  Then I'd stick to shuffle board.

I've been teaching myself Ruby the last couple months and just recently started going through the problems on Project Euler.  Problem 3 posed the following question:

The prime factors of 13195 are 5,7,13, and 29
What is the largest prime factor of the number 600851475143?

From wikipedia, "In number theory, the prime factors of a positive integer are the prime numbers that divide into that integer exactly, without leaving a remainder."

My solution to the problem in Ruby is below:

The first dilemma I faced while solving the problem was generating a list of prime numbers.  I'm going to be honest, I didn't generate squat.  I kind of cheated.  I found a list of 10,000 prime number online.  When the class PrimeFactorFinder is initialized, the list of numbers is opened, the prime numbers are "scanned" in using Regular Expressions and added to the array @PrimeNumbers.  There is an way to actually generate prime numbers in Ruby I discovered.  One can use the mathn standard ruby library as seen below:

require 'mathn'
primes = Prime.new
factor = primes.next

The next hurdle was finding the list of prime factors.  This was found by modulo(ing) the numberToFactor by each prime number. If the former expression yields '0′ then the prime number divides into the numberToFactor exactly and is a 'Prime Factor.'

All in all a pretty simple exercise, yet it required me to use Ruby's Arrays, File IO, and Regular Expressions. Code Kata indeed.

Written by codingwithoutcomments

August 28th, 2008 at 1:20 pm

Creating a IRC (Internet-Relay-Chat) Client in Ruby - First Steps

with one comment

Homer was the beginning of my IRC obsession.  Homer was an IRC client for the Macintosh operating system in the 1990's.  I still kind of remember what it looked like.  It had a black background with white text.  Everytime you typed something, a little animated Homer (Simpson) would dance around in the left hand corner of the screen.  For years I would come home from school, hit the computer, and spend hours talking to people all over the world.  IRC is and was the original chat (ok besides BBSess).  It was fascinating.

The other day I was contemplating what kind of project I could work on that incorporates Ruby as the back-end and Shoooes as the front-end and IRC came to mind as a viable project idea.  I asked the nice people at Stackoverflow how one might get started on this particular project idea (besides knowing Ruby and shoes), and they were nice enough to link me to some important documents.  The wikipedia entry provided a good overall overview while the nitty gritty IRC specification details can be found in RFC 1459.

Pre-Existing Ruby Client

I did a quick search on google for 'IRC' and 'Ruby' and came across Lurker's Blog.  Lurker coded a very basic command line IRC Client which already provides the following functionality:

What can it do?
1) join and talk to multiple channels, as well as handle private chats (what is just enough for most of the people out there)
2) change user mode
3) send any IRC command entered by user (but you do have to know what you are doing and you do it at your own risk)
4) receive dcc file sends (resume supported)
5) process dcc download queue
6) record channel conversations to file

Lurker's code (which can be found here), to me, seems like a perfect jumping-off point for understanding exactly how IRC works while providing the basic IRC functionality for my project.   I messaged Lurker and asked if I could use some of his code in my project and he gave me his blessing.  Over the next few weeks I intend to take the following steps towards my graphical Ruby IRC client.

  1. I'll first take time to understand Lurker's Pre-Existing Code.  I'll go through the code, comment it, then talk about it's overall structure and methodology on this blog.
  2. Lay down Lurker's Pre-Existing code in the Model-View-Controller Framework.  MVC is a powerful design pattern that helps isolate the guts of the code (The Controller) with the Graphical Front-End (The View).  On this blog, I'll talk about how to implement MVC in Ruby.
  3. Design the GUI in Shoes.  Make some pretty drawings.  Post them online.
  4. Code the GUI in Shoes based on the pre-existing basic IRC functionality.
  5. Continue to add additional features to Luker's basic IRC code as the need arises.

Written by codingwithoutcomments

August 27th, 2008 at 5:54 pm

Posted in Programming

Tagged with , , , , , , , ,

Blogging Shoooooes. The Simple-Accordian Application.

without comments

shoooes!

shoooes!

Shooooes is a cross-platform magical GUI library for Ruby created by the notorious whytheluckystiff author of Why's Poinant Guide to Ruby and Try Ruby! (in your browser). Yes, he is busy to the infinite power.  I am a big fan of all his work.

Included with the Shooooes software, is a frighteningly large pack of sample applications.  These sample applications are fun, swift, and swiun (a combination fo both swift and fun).  What they aren't, however, is well commented.  (They are, in fact, zero commented.)  I do understand _why's reasoning though.  Cluttering code up with comments makes it harder to read, but easier to understand.  I'd advise, trying to figure out the program with the un-commented version first, but if you hit a snag, know that the commented version is there for a little guidance.

Simple-Accordion

Today's Application is the Simple Accordion.  If you don't have the code you can download it here, or if you want to download the commented version of the Simple-Accordion then click here.

Simple-Accordion.rb

Simple-Accordion.rb

The Simple-Accordion is a relatively simple application that displays three poems that _why composed.  Each poem has a header "0.0″, "0.1″ and "0.2″.  Only one poem is displayed on the screen at a time, the others are hidden under their header.  When the header of an undisplayed poem is clicked, the currently displayed poem is hidden and the undisplayed poem is shown using an accordian like swoop animation.  Very cool.

GUI-Layout

I think the most important thing to understand about this program is the layout of the GUI.  The GUI is composed of six stacks, three slots, and one flow.  Let me explain.  The main window is a flow.  To the main window, three slots are added each with two stacks (one for the header, one for the poem).  When the program is first started, all six stacks are added to the GUI window, but only four stacks are being shown at one time:  Three header stacks and one poem stack.  When the user clicks on a header item, the stack belonging to that header transitions to "fully shown" while the previous stack transitions to "hidden".

For example, clicking on the "0.2″ header hides the poem Stack 2 and Stack 4 while showing the poem in Stack 6.  We will look at how this is done below.

Open_Page Function

When a user clicks on a header item (0.0, 0.1, or 0.2), the open_page function is called and sent the stack item underneath the header that was clicked.  For example, using the picture above, if the Header '0.0′ were clicked, the open_page function would be sent Stack 2.

def open_page stack
 
  active = app.contents.map { |x| x.contents[1] }.
  detect { |x| x.height > 0 }
 
  return if active == stack
 
  a = animate 60 do
    stack.height += 20
    active.height = 240 - stack.height if active
    a.stop if stack.height == 240
  end
end

The first item of business in the open_page function is determining the currently active poem stack (the stack with the visible poem).  In our picture above, the currently active poem stack is Stack 6.  The app.contents.map function sends each slot in the GUI to the block of code to the right of the function call.  The slot is represented by the variable x.  Remember, each slot contains two stacks.  The first stack is the header stack.  The second stack is the poem stack.  We are, at the moment, only interested in the height of the poem stack which is the second item in the slot, thus x.contents[1]Detect is then called on that stack to see if the poem stack's height is greater then zero.  If it is, then it is the currently active poem stack and is returned to the variable entitled 'active.'

If the currently active poem stack equals the stack sent to the open_page function, then nothing is to be done and the function returns.  This functionality can be observed in the picture above.  If the header '0.2′ were clicked at this point, the poem under the '0.2′ header is already active, therefore there is nothing further to be done.

If, however, the header '0.0′ is clicked, an animation event is activated at 60 frames per second.  On each frame, Stack 2's height is increased by 20 pixels, while Stack 6's height is decreased by 20 pixels.  This continues until Stack 2's height is now 240 pixels and Stack 6's height is 0 pixels (or hidden).  This produces the fun accordion animation that you know and love.

Phew.

That was the most complex part of the code.  If you can understand that, you can for sure definitely understand the rest. I'm not going to go through it all, however, I am going to talk about a few places in the code that are clever or interesting.

More Ruby Fun

The first item I'd like to talk is not a function of Shoooes, but a function of Ruby that I had never seen before.  The page function is called, and two strings are sent to that function as the 'title' and 'text' variables.  All the text between <<-'END' and END is captured and sent to the 'text' variable formatting intact.  This is a great way of capturing a bunch of text whose formatting you want to preserve into a variable.

page "0.0", <<-'END'
There is a thought
I have just had
Which I don’t care to pass to
Anyone at all at this time.
 
I have even forgotten it now,
But kept only the pleasures
Of my property
And of my controlled mental slippage.
END

The first line of the page function is a cool trick for seeing if an array is initialized or not.  You simply OR it with itself.  If the @pages array already exists, @pages will be simply set equal to itself.  If it doesn't exist, however, @pages will be set to a new array.

@pages ||= []

Remember, if you have any more questions about the Simple-Accordian, snag the commented code.  It should answer most of your questions.

Written by codingwithoutcomments

August 21st, 2008 at 5:54 pm