Adjacency list representation of undirected graph in ruby

Ruby program for Adjacency list representation of undirected graph. Here problem description and explanation.

#    Ruby Program for 
#    Undirected graph representation by using adjacency list 
class AjlistNode 
	# Define the accessor and reader of class AjlistNode
	attr_reader :id, :next
	attr_accessor :id, :next
	#  Vertices node key
	def initialize(id) 
		#  Set value of node key
		self.id = id
		self.next = nil
	end

end

class Vertices 
	# Define the accessor and reader of class Vertices
	attr_reader :data, :next, :last
	attr_accessor :data, :next, :last
	def initialize(data) 
		self.data = data
		self.next = nil
		self.last = nil
	end

end

class Graph 
	# Define the accessor and reader of class Graph
	attr_reader :size, :node
	attr_accessor :size, :node
	#  Number of Vertices
	def initialize(size) 
		#  Set value
		self.size = size
		self.node = Array.new(size) {nil}
		self.setData()
	end

	#  Set initial node value
	def setData() 
		if (self.size <= 0) 
			print("\nEmpty Graph\n")
		else
 
			index = 0
			while (index < self.size) 
				self.node[index] = Vertices.new(index)
				index += 1
			end

		end

	end

	#  Connect two nodes
	def connect(start, last) 
		edge = AjlistNode.new(last)
		if (self.node[start].next == nil) 
			self.node[start].next = edge
		else
 
			#  Add edge at the end
			self.node[start].last.next = edge
		end

		#  Get last edge 
		self.node[start].last = edge
	end

	#   Handling the request of adding new edge
	def addEdge(start, last) 
		if (start >= 0 && start < self.size && 
            last >= 0 && last < self.size) 
			self.connect(start, last)
			if (start == last) 
				#  When self loop
				return
			end

			self.connect(last, start)
		else
 
			#  When invalid nodes
			print("\nHere Something Wrong\n")
		end

	end

	def printGraph() 
		if (self.size > 0) 
			index = 0
			#  Print graph ajlist Node value
			while (index < self.size) 
				print("\nAdjacency list of vertex ", index ," :")
				temp = self.node[index].next
				while (temp != nil) 
					#  Display graph node 
					print("  ", self.node[temp.id].data)
					#  Visit to next edge
					temp = temp.next
				end

				index += 1
			end

		end

	end

end

def main() 
	#  5 implies the number of nodes in graph
	g = Graph.new(5)
	#  Connect node with an edge
	g.addEdge(0, 1)
	g.addEdge(0, 2)
	g.addEdge(0, 4)
	g.addEdge(1, 2)
	g.addEdge(1, 4)
	g.addEdge(2, 3)
	g.addEdge(3, 4)
	#  print graph element
	g.printGraph()
end

main()

Output

Adjacency list of vertex 0 :  1  2  4
Adjacency list of vertex 1 :  0  2  4
Adjacency list of vertex 2 :  0  1  3
Adjacency list of vertex 3 :  2  4
Adjacency list of vertex 4 :  0  1  3


Please share your knowledge to improve code and content standard. Also submit your doubts, and test case. We improve by your feedback. We will try to resolve your query as soon as possible.

New Comment







© 2021, kalkicode.com, All rights reserved