Entries Tagged 'Programming' ↓

Fibbing a Sequence

The Fibonacci sequence is a one of those mathematical formulas that I learned in grade school and promptly went in one ear and out the other. This formula solved a rabbit breeding problem that Fibonacci created in one of his works in 1202. Recursive in nature, the formula creates a sequence of numbers where the sum of the last two numbers in the sequence create the next number.

For the first two numbers in the sequence they are defined as follows.

F(n) = 0 \text{ if } n = 0
F(n) = 1 \text{ if } n = 1

The next number is the sum of the last two numbers in the sequence.

F(n) = F(n - 2) + F(n - 1) \text{ if } n > 1

By substituting the first two known numbers, the third number in the sequence would be.

F(2) = F(0) + F(1) = 0 + 1 = 1

And the fourth number would be.

F(3) = F(1) + F(2) = 1 + 1 = 2

The following Ruby program computes the Fibonacci sequence, using an array fibonacci_seq to store calculated numbers in the sequence. This makes it easy to compute higher numbers for F(n) where n > 1, as the numbers are easily accessible in the array.

Note: Due to some quirks in the Wordpress’ new sourcecode feature, I am unable to display the less-than symbol. I’ve had to use the greater-than symbol in conditionals where I wouldn’t normally put them.


# Generates the sequence of Fibonacci numbers starting
# from F(0) and ending at F(_max_amount_) where F is
# the Fibonacci formula.
# [+max_amount+]  The highest fibonacci number to
#                 generate in the sequence.
def generate_fibonacci_seq(max_amount)
  n = 0
  # An array of Fibonacci numbers
  fibonacci_seq = Array.new

  if (max_amount >= 0) then
    while (max_amount >= n)
      if n == 0 then
        # F(0) = 0
        fibonacci_seq.push(0)
      elsif n == 1 then
        # F(1) = 1
        fibonacci_seq.push(1)
      else
        # F(n) = F(n - 2) + F(n - 1)
        last_two_numbers = fibonacci_seq.last(2)
        fibonacci_seq.push(last_two_numbers[0] + last_two_numbers[1])
      end

      n = n + 1
    end
  end

  return fibonacci_seq
end

# Generate the first 32 Fibonacci numbers
fib_seq = generate_fibonacci_seq(31)
puts fib_seq

Ruby Rant: The abbreviated form of the conditional keyword elsif annoys me because other programming languages spell out the phrase as else if. I’d personally prefer being able to switch from one programming language to another without worrying these inconsistencies. One day I’m going to type an elsif in PHP and have my editor flag the conditional keyword as an error.

The output of the first five numbers are:

0
1
1
2
3

I’d prefer to display the number in a list that flows horizontally. The Array class provides a method each which iterates through each element in the array. Ruby provides a nice feature for quickly processing iterators, in this case the iterator is the each method, with a feature known as blocks. A (code) block appears to the right of the iterator method between braces {code_block}.


# Generate the first 32 Fibonacci numbers
fib_seq = generate_fibonacci_seq(31)
fib_seq.each { |element| print "#{element} " }
print "\n"

Within a block, the parameter appears between two pipe symbols |parameter|. In the above example, the parameter is element. To the right of the parameter are instructions for processing the element. For each element that I encounter, I’ll print the element with a trailing space to separate the next number.

Using the each iterator, the output for the first 32 number of the Fibonacci sequence is:

0 1 1 2 3 5 8 13 21 34 55 89 144 233 377 610 987 1597 2584 4181 6765 10946 17711 28657 46368 75025 121393 196418 317811 514229 832040 1346269

Hello World

As with any introduction to a programming language, I start off with a simple Hello World program. What takes me a minute to do in a language that I know, takes much longer with one that is foreign to me.

I’ll make this a bit more complicated, asking for the person’s name and telling them hello in my reply.


# Ask the user their name
puts "What is your name?"
user_name = gets

# Cunningly impress them with your response
puts "Hello, #{user_name.capitalize}!"

When I run the program and it asks for my name, I’ll type in Joe.

Output:

What is your name?
joe
Hello, Joe
!

The output of the program is not quite what I envisioned. The exclamation point appears on separate line. When I typed joe and pressed enter, the enter (or newline) is printed in the response. String object provides a method, chomp, that will move unwanted display characters, namely the enter key that I pressed. I’ll call chomp when I receive the input from the gets method.


# Ask the user their name
puts "What is your name?"
# Get the user name and remove newline characters
user_name = gets.chomp

# Cunningly impress them with your response
puts "Hello, #{user_name.capitalize}!"

Running the revised program, I hope that the response appears on one line when I tell the program that my name is Joe.

Output:

What is your name?
joe
Hello, Joe!

There you have it. My first Hello World program written in Ruby.