=begin rdoc Methods in this module are not intended to be used by students. They are implemented here so they can be tested before being included in the book or lecture slides. Instructors can also load this module to use the methods in lectures. =end module RubyLabs module Demos =begin rdoc Convert the temperature +f+ (in degrees Fahrenheit) into the equivalent temperature in degrees Celsius. =end def celsius(f) (f - 32) * 5 / 9 end =begin rdoc This version of the Sieve of Eratosthenes iterates until the worklist is empty. Use it as a baseline for counting the number of iterations, to compare it to the actual version that iterates until finding the first prime greater than sqrt(n) =end def sieve(n) worklist = Array(2..n) primes = [] while worklist.length > 0 primes << worklist.first worklist.delete_if { |x| x % primes.last == 0 } end return primes end def sequence(i,j) Array(i..j) end =begin rdoc The HashLab module has preliminary versions of insert and lookup methods that don't use buckets; these are the final versions, with buckets. =end def insert(s, t) i = h(s, t.length) t[i] = Array.new if t[i].nil? t[i] << s return i end def lookup(s, t) i = h(s, t.length) if t[i] && t[i].include?(s) return i else return nil end end =begin rdoc This is the bare bones version of Eliza.transform, the method that applies transformation rule to make a response to a sentence. =end def transform(sentence) queue = PriorityQueue.new Eliza.scan(sentence, queue) response = nil while queue.length > 0 rule = queue.shift response = Eliza.apply(sentence, rule) break if response != nil end return response end =begin rdoc Compare two ways of writing a loop =end def loops(n) i = 1 while i <= n puts i ** 2 i += 1 end for i in 1..n puts i**2 end end =begin rdoc Simple demonstration of why nested loops lead to n^2 operations. This version is for a loop structure like the one in isort, but it also works for any algorithm that needs all (i,j) pairs and that is symmetric, i.e. (i,j) = (j,i). =end # :begin :nested def nested(n) count = 0 i = 0 while i < n j = 0 while j < i count += 1 j += 1 end i += 1 end return count end # :end :nested # code used in figure next to nested def isnest(n) i = 1 while i < n j = i-1 while j >= 0 puts "i = #{i}, j = #{j}" j = j-1 end i = i+1 end end end # Demos end # RubyLabs