module RubyLabs module LinearDSLab #VERSION 1.2 #Labelled top and bottom of stack, front and end of queue #Added a line after Lab title # A Struct is a convenient way to bundle a number of attributes together, using accessor methods, without having to write an explicit class. This StackView object is being used to store the location of all the rectangles, and its corresponding values. StackView = Struct.new(:cells, :values) # Generates the view for a stack visualization def view_stack(s, *peek) # Initializes the canvas and font type Canvas.init(400, 400, "Stack") Canvas::Font.new('bucketfont', :family => 'Helvetica', :size => 11) stack = s.items cells = [] values = [] # Define starting height of first rectangle y0 = 50 Canvas::Text.new("Stack Lab", 10, 1, {:font => :bucketfont}) Canvas::Line.new(0, 20, 400, 20, :fill => :gray, :width => 1) # If generating a peek view, color first rectangle red, and place it on the right if peek[0] && stack[0] cells << Canvas::Rectangle.new(10, y0, 60, y0+25) cells[0].fill = 'red' y1 = y0+3 values << Canvas::Text.new(stack[0], 65, y0+3, {:font => :bucketfont}) Canvas::Text.new("<- Top of the Stack", 200, y1, {:font => :bucketfont}) # Else place a normal rectangle elsif stack[0] cells << Canvas::Rectangle.new(10, y0, 60, y0+25) cells[0].fill = 'grey' y1 = y0+3 values << Canvas::Text.new(stack[0], 65, y0+3, {:font => :bucketfont}) Canvas::Text.new("<- Top of the Stack", 200, y1, {:font => :bucketfont}) end iterations = stack.length-1 # Iterate as many times as the number of elements in the array minus one. The first element is already handled above. iterations.times do |i| y0 += 25 # Draw a rectangle and store a reference to this rectangle in the cells array cells << Canvas::Rectangle.new(10, y0, 60, y0+25) cells[i+1].fill = 'grey' # Draw the text value and store a reference to this value in the values array values << Canvas::Text.new(stack[i+1], 65, y0+3, {:font => :bucketfont}) end if stack.length-1 > 0 Canvas::Text.new("<- Bottom of the Stack", 200, y0+3, {:font => :bucketfont}) end # Store the properties of this drawing as a Struct object s.drawing = StackView.new(cells, values) return true end # Ruby Array-based implementation of a Stack class Stack # array used to store the values in the stack attr_reader :items # Struct object to store the attributes of the drawn visualization attr_accessor :drawing # class constructor def initialize @items = Array.new end # pop method. if a drawing exists, redraw the canvas def pop value = items.shift if @drawing view_stack(self, false) end return value end # peek method. if a drawing exists, redraw the canvas def peek if @drawing view_stack(self, true) end return items.first end # push method. if a drawing exists, redraw the canvas def push(value) output = items.unshift(value) if @drawing view_stack(self, false) end return output end # return a string representation of the array def inspect return to_s end # returns a string representation of the array def to_s return @items.inspect end # returns the number of items currently in the stack def count return items.count end end # A Struct is a convenient way to bundle a number of attributes together, using accessor methods, without having to write an explicit class. This QueueView object is being used to store the location of all the rectangles, and its corresponding values. QueueView = Struct.new(:cells, :values) # Generates the view for a queue visualization def view_queue(q, *peek) # Initializes the canvas and font type Canvas.init(400, 400, "Queue") Canvas::Font.new('bucketfont', :family => 'Helvetica', :size => 11) queue = q.items cells = [] values = [] # Define starting height of first rectangle y0 = 50 Canvas::Text.new("Queue Lab", 10, 1, {:font => :bucketfont}) Canvas::Line.new(0, 20, 400, 20, :fill => :gray, :width => 1) # If generating a peek view, color last rectangle red, and place it on the right if peek[0] && queue[0] cells << Canvas::Rectangle.new(10, y0, 60, y0+25) cells[0].fill = 'red' y1 = y0+3 values << Canvas::Text.new(queue[0], 65, y1, {:font => :bucketfont}) Canvas::Text.new("<- Head of the Queue", 200, y1, {:font => :bucketfont}) # Else place a normal rectangle elsif queue[0] cells << Canvas::Rectangle.new(10, y0, 60, y0+25) cells[0].fill = 'grey' y1 = y0+3 values << Canvas::Text.new(queue[0], 65, y1, {:font => :bucketfont}) Canvas::Text.new("<- Head of the Queue", 200, y1, {:font => :bucketfont}) end iterations = queue.length-1 # Iterate as many times as the number of elements in the array minus one. The first element is already handled above. iterations.times do |i| y0 += 25 # Draw a rectangle and store a reference to this rectangle in the cells array cells << Canvas::Rectangle.new(10, y0, 60, y0+25) cells[i+1].fill = 'grey' # Draw the text value and store a reference to this value in the values array values << Canvas::Text.new(queue[i+1], 65, y0+3, {:font => :bucketfont}) end if queue.length-1 > 0 Canvas::Text.new("<- Tail of the Queue", 200, y0+3,{:font => :bucketfont}) end # Store the properties of this drawing as a Struct object q.drawing = QueueView.new(cells, values) return true end # Ruby Array-based implementation of a queue class Queue # array used to store the values in the queue attr_reader :items # Struct object to store the attributes of the drawn visualization attr_accessor :drawing # class constructor def initialize @items = Array.new end # dequeue method. if a drawing exists, redraw the canvas def dequeue value = items.shift if @drawing view_queue(self, false) end return value end # peek method. if a drawing exists, redraw the canvas def peek if @drawing view_queue(self, true) end return items.first end # enqueue method. if a drawing exists, redraw the canvas def enqueue(value) output = items << value if @drawing view_queue(self, false) end return output end # enqueue method. an alternative. def <<(value) output = items << value if @drawing view_queue(self, false) end return output end # dequeue method. an alternative. def shift value = items.shift if @drawing view_queue(self, false) end return value end # return a string representation of the array def inspect return to_s end # returns a string representation of the array def to_s return @items.inspect end # returns the number of items currently in the queue def count return items.count end end # checks whether an array is a palindrome using both stack and queue # :begin :is_palindrome def is_palindrome(v) t = v.split(//) q = Queue.new s = Stack.new t.each { |x| q.enqueue(x) } t.each { |x| s.push(x) } while s.count > 0 left = q.dequeue right = s.pop return false if(left != right) end return true end # :end :is_palindrome # checks whether an array contains balanced braces using stack # :begin :check_braces def check_braces(t) s = Stack.new balancedSoFar = true i = 0 while i < t.count and balancedSoFar if t[i] == "{" s.push(t[i]) elsif t[i] == "}" if s.count > 0 s.pop else balancedSoFar = false end end i += 1 end return (balancedSoFar and s.count==0) end # :end :check_braces # :begin :fibonacci_stack def fibonacci_stack(n) s = Stack.new s.push(n) result = 0 while s.count > 0 current = s.pop if current == 0 result += 0 elsif current == 1 result += 1 else s.push(current - 2) s.push(current - 1) end end return result end # :end :fibonacci_stack # :begin :fibonacci def fibonacci(n) if n == 0 return 0 elsif n == 1 return 1 else return fibonacci(n-1) + fibonacci(n-2) end end # :end :fibonacci # This recursive version of binary search is taken from RubyLabs (John Conery's book). # :begin :rbsearch def rbsearch(a, k, lower = -1, upper = a.length) mid = (lower + upper)/2 return nil if upper == lower + 1 return mid if k == a[mid] if k < a[mid] return rbsearch(a, k, lower, mid) else return rbsearch(a, k, mid, upper) end end # :end :rbsearch # non-recursive, stack-based version of binary searh # :begin :rbsearch_stack def rbsearch_stack(a, k, lower = -1, upper = a.length) s = Stack.new s.push(lower) s.push(upper) while s.count > 0 upper = s.pop lower = s.pop mid = (lower + upper)/ 2 return nil if upper == lower + 1 return mid if k == a[mid] if k < a[mid] s.push(lower) s.push(mid) else s.push(mid) s.push(upper) end end end # :end :rbsearch_stack # This brackets method is taken from RubyLabs (John Conery's book). # A helper method that can be called from a probe to display the contents # of an array during a search or sort. See also IterationLab#brackets. # # The version implemented in this module accepts an additional argument, # which specifies the location of the right bracket in the output string # (if this argument is not give the right bracket is inserted at the end). # # An optional third argument, intended for experiments with binary search, tells # the method where to insert an asterisk before an item. # # Examples: # # >> a = TestArray.new(15) # => [22, 3, 70, 74, 35, 0, 82, 64, 90, 54, 88, 26, 75, 18, 17] # >> puts brackets(a, 8, 10) # 22 3 70 74 35 0 82 64 [90 54 88] 26 75 18 17 # => nil # >> puts brackets(a, 8, 10, 9) # 22 3 70 74 35 0 82 64 [90 *54 88] 26 75 18 17 # => nil # def brackets(a, left, right = a.length-1, mid = nil) left = 0 if left < 0 right = a.length-1 if right >= a.length pre = left == 0 ? "" : " " + a.slice(0..(left-1)).join(" ") + " " inner = left <= right ? a.slice(left..right).join(" ") : "" post = " " + a.slice(right+1..-1).join(" ") res = pre + "[" + inner + "]" + post if mid && left < right res[res.index(a[mid].to_s)-1] = ?* end return res end end end