module GraphLab =begin doc == Graph A Graph is made up of vertices and edges between vertices. In this lab, to represent edges, we use adjacency list to represent an directed graph. Vertex position will be created randomly. =end # Version 2.7 # Change log: #1. added method g.deleteEdges(v1,v2) #2. added another constructor where user can define x coord and y coord for the vertex created @@graph = nil @@visitedV = Array.new @@position = Array.new #to keep track of position of vertex in canvas @@createdValues = Array.new #to keep track of created value #method to view graph def view_graph(graph) @@graph = graph raise "Value must be a Graph!" if graph.class != GraphLab::Graph # Initializes the canvas and font type Canvas.init(650, 650, "GraphLab") Canvas::Font.new('bucketfont', :family => 'Helvetica', :size => 14) Canvas::Font.new('visitedfont', :family => 'Helvetica', :size => 12) if (graph.vertices == nil) return true end if(graph.vertices != nil) draw_graph(graph) end return true end def graph @@graph end #called by view graph, to draw GRAPH, calls draw vertices and draw edge def draw_graph(g) v = g.vertices #to draw edges v.each { |vertex| draw_ed(vertex.xcoord,vertex.ycoord, vertex.adjList, vertex.value)} #to draw the vertices v.each { |x| draw_v(x.xcoord,x.ycoord, x.value,"gray") } end #to draw vertices def draw_v(x,y,value,color) Canvas::Circle.new(x, y, 18, :fill => color) Canvas::Text.new(value, (x-8), (y-8), :font => 'bucketfont') end #to call drawedge for each adj def draw_ed(x1,y1,adjList,val1) adjList.each { |a| draw_edge(x1,y1, a.xcoord, a.ycoord, val1, a.value)} end #to draw edges def draw_edge(x1,y1,x2,y2, val1, val2) Canvas::Line.new(x1,y1,x2,y2) arrowLengthx = (x2-x1) arrowLengthx = arrowLengthx.abs arrowLengthx = (arrowLengthx - 9.0)*0.03 arrowLengthy = (y2-y1) arrowLengthy = arrowLengthy.abs arrowLengthy = (arrowLengthy - 9.0)*0.03 #to mark the directed graph from the source to the adj node e.g. node 5 had adj node 4, mark will be *4 x5= 0.0 y5= 0.0 distnce = 9.0 dist = 7.0 if(arrowLengthx < arrowLengthy && (arrowLengthx/0.03) >= 60) distnce = 8.8 dist = 7.0 elsif(arrowLengthx < arrowLengthy) distnce = 2.8 dist = 2.5 elsif(arrowLengthx > arrowLengthy && (arrowLengthy/0.03) >= 60) distnce =8.8 dist = 7.0 elsif(arrowLengthx > arrowLengthy) distnce = 2.8 dist = 2.2 end if(x2y2) x5 = ((x1-x2)/distnce)+x2 y5 = ((y1-y2)/distnce)+y2 elsif(x2x1 && y1x1 && y1>y2) x5 = x2-((x2-x1)/distnce) y5 = ((y1-y2)/distnce)+y2 end x0= 0.0 y0= 0.0 gradient =(((y2*-1.0)-(y1*-1.0))/(x2-x1)) c= (y2*-1.0)-(gradient*x2) if(x2y2) x0 = ((x1-x2)/dist)+x2 y0 = ((y1-y2)/dist)+y2 elsif(x2x1 && y1x1 && y1>y2) x0 = x2-((x2-x1)/dist) y0 = ((y1-y2)/dist)+y2 end gradientPerpendicular = (1.0/gradient)*-1.0 cPerpendicular = (y0*-1.0) - (gradientPerpendicular*x0) if(arrowLengthx < arrowLengthy && arrowLengthx >= 60) arrl = arrowLengthx x3 = x0 - arrl y3 = (x3*gradientPerpendicular + cPerpendicular)*-1.0 x4 = x0 + arrl y4 = (x4*gradientPerpendicular + cPerpendicular)*-1.0 elsif(arrowLengthx < arrowLengthy) arrl = 9.0 x3 = x0 - arrl y3 = (x3*gradientPerpendicular + cPerpendicular)*-1.0 x4 = x0 + arrl y4 = (x4*gradientPerpendicular + cPerpendicular)*-1.0 elsif(arrowLengthx > arrowLengthy && arrowLengthy >=60) arrl = arrowLengthy y3 = (-y0 - arrl)*-1.0 x3 = (-y3-cPerpendicular)/gradientPerpendicular y4 = (-y0 + arrl)*-1.0 x4 = (-y4-cPerpendicular)/gradientPerpendicular elsif(arrowLengthx > arrowLengthy) arrl = 9.0 y3 = (-y0 - arrl)*-1.0 x3 = (-y3-cPerpendicular)/gradientPerpendicular y4 = (-y0 + arrl)*-1.0 x4 = (-y4-cPerpendicular)/gradientPerpendicular end Canvas::Line.new(x3,y3,x5,y5) Canvas::Line.new(x4,y4,x5,y5) end def dfs(s) @@visitedV << "DFS order of visit: " view_graph(self) _dfs(s) self.clearAll @@visitedV.clear return nil end #to perform dfs with x as the starting node, recursive def _dfs(v) setVisitedDfs(v) #recursive dfs v.adjList.each{ |u| setVisitedDfs(u) } end def setVisitedDfs(u) if(!u.isVisited?) u.visited = true p u @@visitedV << u anim(u) _dfs(u) end end #to perform bfs with x as the starting node, using queue implementation def bfs(s) @@visitedV << "BFS order of visit: " view_graph(self) @q = Queue.new setVisitedBfs(s) while (!@q.isEmpty?) v = @q.dequeue adjList = v.adjList adjList.each { |u| setVisitedBfs(u)} end self.clearAll @@visitedV.clear return nil end def setVisitedBfs(u) if(!u.isVisited?) u.visited = true p u @@visitedV << u anim(u) @q.enqueue(u) end end def clearAll self.vertices.each { |u| u.visited = false} end def anim(s) draw_v(s.xcoord,s.ycoord, s.value,"red") Canvas::Text.new(@@visitedV.to_s, 30, 600, :font => 'visitedfont') sleep(1.5) draw_v(s.xcoord,s.ycoord, s.value, "green") end class Graph #to keep array of vertices attr_reader :vertices # class constructor def initialize @vertices = Array.new end # checks whether the graph is empty def isEmpty? return vertices == nil end #to add new vertex in the graph def addVertex(vertex) raise "Value must be a Vertex!" if vertex.class != GraphLab::Vertex raise "Vertex already added in the graph!" if vertices.include?(vertex) if(vertex.class == GraphLab::Vertex && !vertices.include?(vertex)) vertices << vertex end view_graph(self) return @vertices end #to draw edges between 2 vertices in graph randomly from v1 to v2 def addEdge(v1,v2) raise "Value must be a Vertex!" if v1.class != GraphLab::Vertex raise "Value must be a Vertex!" if v2.class != GraphLab::Vertex raise "Vertex already added in the graph!" if v1.adjList.include?(v2) if(v1.class == GraphLab::Vertex && v2.class == GraphLab::Vertex && !v1.adjList.include?(v2)) v1.addEdge(v2) end view_graph(self) end def deleteEdge(v1, v2) raise "Value must be a Vertex!" if v1.class != GraphLab::Vertex raise "Value must be a Vertex!" if v2.class != GraphLab::Vertex raise "Vertex "+v1.value.to_s+" does not have "+v2.value.to_s+" edge" if !v1.adjList.include?(v2) if(v1.class == GraphLab::Vertex && v2.class == GraphLab::Vertex && v1.adjList.include?(v2)) v1.deleteEdge(v2) end view_graph(self) end #to draw edges between 2 vertices in graph randomly def addEdges(x) raise "Value must be smaller than 1!" if x > 1 raise "Value must be larger than 0!" if x <= 0 x = x*100 vertices.each { |u| drawOrNot(u,vertices,x) } view_graph(self) end def drawOrNot(u,adjList,x) adjList.each{ |o| drawNot(u,o,x) } end def drawNot(u,o,x) a = rand(101) #from 100, what is the generated random no if(a<=x && u!=o) addEdgeForGraph(u,o) end end #to add edge from v1 to v2 - directed graph def addEdgeForGraph(v1,v2) raise "Value must be a Vertex!" if v1.class != GraphLab::Vertex raise "Value must be a Vertex!" if v2.class != GraphLab::Vertex raise "Vertex must be in the graph" if !include?(v1) raise "Vertex must be in the graph" if !include?(v2) raise "Vertex "+v2+" already adjacent vertex of "+v1+" in the graph!" if v1.adjList.include?(v2) raise "cannot add edge to itself" if v1 == v2 if(v1.class == GraphLab::Vertex && v2.class == GraphLab::Vertex && include?(v1) && include?(v2)) v1.addEdge(v2) end end #to count number of vertices in the graph def count_v() return vertices.length end #to delete the vertex from the graph def deleteVertex(vertex) if(vertex.class == GraphLab::Vertex) for i in 0..graph.vertices.length-1 vi = graph.vertices[i] if(vi.adjList.include?(vertex)) vi.adjList.delete(vertex) end end vertex.adjList.each { |adj| adj.adjList.delete(vertex)} vertex.adjList.clear vertices.delete(vertex) end view_graph(self) return @vertices end def include?(v1) return vertices.include?(v1) 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 @vertices.inspect end end class Vertex # value and coordinate of vertex attr_accessor:value attr_accessor:xcoord attr_accessor:ycoord # attribute that represents the node in a graph canvas attr_accessor:adjList attr_accessor:visited def initialize *args case args.size when 3 init_valxy *args when 1 init_val *args else error end end def init_valxy(value, x , y) raise "Enter other value. Vertex with this value has been created!" if @@createdValues.include?(value) if(!@@createdValues.include?(value)) @@createdValues << value @value = value @xcoord = x @ycoord = y @adjList = Array.new @visited = false end return @value end def init_val(value) raise "Enter other value. Vertex with this value has been created!" if @@createdValues.include?(value) if(!@@createdValues.include?(value)) @@createdValues << value @value = value @xcoord = rand(450)+30 @ycoord = rand(450)+30 coord = (xcoord.to_s + ycoord.to_s) #to avoid overlapping vertex coordinates in canvas while (@@position.include?(coord)) puts "regenerate to avoid collision" @xcoord = rand(450)+30 @ycoord = rand(450)+30 coord = (xcoord.to_s + ycoord.to_s) end #@@position << coord #need to add more y coord and x coord a = 50 x = @xcoord - a y = @ycoord - a for i in 0..100 x = x + i for j in 0..100 y = y + j coord = (x.to_s + y.to_s) @@position << coord end end @adjList = Array.new @visited = false end return @value end def getAdjList() return self.adjList end #to add edge to this vertex def addEdge(vertex) raise "Value must be a Vertex!" if vertex.class != GraphLab::Vertex raise "cannot add edge to itself" if vertex == self adjList << vertex end def deleteEdge(vertex) raise "Value must be a Vertex!" if vertex.class != GraphLab::Vertex adjList.delete(vertex) end # return a string representation of the vertex def inspect return to_s end # returns a string representation of the vertex def to_s s = value.to_s+" "; #s+= "("+xcoord.to_s+","; #s+= ycoord.to_s+")"; return s; end def isVisited? return @visited end end 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 # 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 def isEmpty? output = false if(@items.size == 0) output = true end return output 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 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 # :begin :visit def visit(vertex) vertex.visited = true p vertex end # :end :visit # :begin :topsort def topsort(graph) graph.clearAll s = Stack.new for i in 0..graph.vertices.length-1 vi = graph.vertices[i] if !vi.isVisited? topsort_dfs(vi, s) end end return s end # :end :topsort # :begin :topsort_dfs def topsort_dfs(vertex, stack) visit(vertex) for i in 0..(vertex.adjList.length-1) neighbor = vertex.adjList[i] if(!neighbor.isVisited?) topsort_dfs(neighbor, stack) end end stack.push(vertex) end # :end :topsort_dfs end