Graphs
A graph is a data structure consisting of a set of vertices (nodes) and a set of edges connecting these vertices. Graphs are widely used to represent relationships between objects, such as social networks, computer networks, and transportation networks. They can be directed (edges have a specific direction) or undirected (edges have no direction).
Graphs can be implemented using various approaches in Ruby. One common approach is to use an adjacency list or adjacency matrix to represent the connections between vertices.
Below is the Ruby program to implement an undirected graph using an adjacency list:
class Graph
def initialize
@adjacency_list = {}
end
def add_vertex(vertex)
@adjacency_list[vertex] = []
end
def add_edge(vertex1, vertex2)
@adjacency_list[vertex1] << vertex2
@adjacency_list[vertex2] << vertex1
end
def neighbors(vertex)
@adjacency_list[vertex]
end
end
graph = Graph.new
graph.add_vertex("A")
graph.add_vertex("B")
graph.add_vertex("C")
graph.add_vertex("D")
graph.add_edge("A", "B")
graph.add_edge("B", "C")
graph.add_edge("C", "D")
puts graph.neighbors("A").inspect # => ["B"]
puts graph.neighbors("B").inspect # => ["A", "C"]
puts graph.neighbors("C").inspect # => ["B", "D"]
puts graph.neighbors("D").inspect # => ["C"]
Output:
How to Implement Data Structures in Ruby?
Data structures are fundamental components of any programming language, allowing developers to organize and manipulate data efficiently. In Ruby, a versatile and expressive language, implementing various data structures is straightforward. In this article, we’ll explore how to implement common data structures such as arrays, linked lists, stacks, queues, trees, graphs, and hashmaps in Ruby. The article focuses on discussing data structures in Ruby.
Table of Content
- Singly-Linked Lists
- Doubly-Linked Lists
- Circular Linked Lists
- Queues
- Stack
- Hash Tables
- Sets
- Binary Trees
- AVL Trees (Adelson-Velsky and Landis Trees)
- Graphs
- Persistent Lists
Contact Us