So the deadline has passed. Has anybody got any code they wish to share?

I'll start off by just posting a partial solution - the piece of code  
people I was training thought was so elegant, but I think is a bit  
ugly. Please bear in mind I wrote this "live" in a classroom, so it's  
far from perfect:

-----

# Seed our first two values
a, b = 0, 1

# Calculte the next number in sequence given two values,
# and return two values
def next_fib(x, y)
   return y, x + y
end

infinite = false
iterations = 10
count = 2

# Just loops over iterations or to infinity
while count <= iterations or infinite
   puts a if count == 2 # Print out a only on first iteration
   puts b # Print out b always
   a, b = next_fib(a, b) # Increment the values
   count += 1
end

# I want a predicate method for numbers to test if the number is
# Fibonnaci so extend the Fixnum class and add my own method
class Fixnum
   # A brute force method, fine for small integers
   # but Wikipedia has a solution more suitable for
   # very large numbers
   def is_fibonnaci?
     a, b = 0, 1
     puts "testing #{self.to_i}"
     while b < self # If smaller, keep going
       a, b = next_fib(a, b) # Note, needs above method
     end
     return true if b == self # If equal, must be Fibonacci
     return false # Otherwise we've gone past it, so return false
   end
end

puts "1 returns #{1.is_fibonnaci?}"
puts "6 returns #{1.is_fibonnaci?}"

-----

The bits that raised eyebrows in my class:

- Returning two values, which is perfectly legal in Ruby. I'd spent  
the morning talking about different ways to return things in Ruby and  
what would happen if I'd done "a = next_fib(a, b)" or ",b =  
next_fib(a, b)" so added this in to make a point more than anything

- "while count <= iterations or infinite" does not test if count is  
less than infinite. While sees two tests here: count <= iterations OR  
infinite. If infinite is true, it will therefore never end

- Extending Fixnum to add my own methods.

- The fact I wait until I've gone past my value and then test for  
equality (in which case it's Fib), otherwise just return false some  
people see as "sloppy" or even "cheating".

Comments? Thoughts? Bring your code out...

--
Paul Robinson

http://vagueware.com :: [EMAIL PROTECTED] :: +44 (0) 7740 465746

Vagueware Limited is registered in England/Wales, number 05700421
Registered Office: 3 Tivoli Place, Ilkley, W. Yorkshire, LS29 8SU
Correspondence:   55 Velvet Court, Granby Row, Manchester, M1 7AB



--~--~---------~--~----~------------~-------~--~----~
You received this message because you are subscribed to the Google Groups 
"NWRUG" group.
To post to this group, send email to [email protected]
To unsubscribe from this group, send email to [EMAIL PROTECTED]
For more options, visit this group at 
http://groups.google.com/group/nwrug-members?hl=en
-~----------~----~----~----~------~----~------~--~---

Reply via email to