Question

A graph consists of nodes and edges. An edge is an (unordered) pair of two distinct...

A graph consists of nodes and edges. An edge is an (unordered) pair of two distinct nodes in the graph. We create a new empty graph from the class Graph. We use the add_node method to add a single node and the add_nodes method to add multiple nodes. Nodes are identified by unique symbols. We call add_edge with two nodes to add an edge between a pair of nodes belonging to the graph. We can also ask a graph for the number of nodes and edges it contains, and for a list of its nodes and edges. The to_s method returns a string representing the graph's adjacency lists. Methods should not change the graph if called with invalid arguments; e.g., adding an edge that is already in the graph or that references a node that does not already belong to the graph. Your code does not have to generate the exact transcript that follows but it should provide this basic functionality.

>> g = Graph.new
=> <Graph: 0, 0>
>> g.add_node(:a)
=> a

>> g.add_nodes([:b, :c]) => [:b, :c]
>> g
=> <Graph: 3, 0>

>> g.get_nodes
=> [:a, :b, :c]
>> g.nbr_nodes
=> 3

>> g.add_edge(:a, :b) => [a, b]
>> g.add_edge(:b, :c) => [b, c]

>> g
=> <Graph: 3, 2>
>> g.get_edges
=> [[a, b], [b, c]]
>> g.nbr_edges
=> 2
>> puts g
a -> b
b -> a,c
c -> b
=> nil

Homework Answers

Answer #1
//C++ implementation for the problem

#include<iostream>
#include<map>
#include<vector>
#include<set>
using namespace std;

class Graph{                                            //Assuming a directed graph
private:
        map<char,vector<char>> edges;       //A map to maintain the edges
        set<char> nodes;                          //A set to maintain nodes, avoiding duplicacy
        int edge_count;                                 //variable to keep track of number of edges
public:
        void add_node(char node) {
                nodes.insert(node);                     //Inserting node to set
        }
        void add_nodes(vector<char> vNodes) {
                for(char node: vNodes)
                        nodes.insert(node);
        }
        bool add_edge(char u, char v) {
                //Checking if both the entered nodes are valid and exists in the set of nodes
                if(nodes.find(u)==nodes.end() || nodes.find(v)==nodes.end())
                        return false;
                edges[u].push_back(v);
                edge_count++;
                return true;
        }
        int nbr_nodes() {
                return (int)nodes.size();
        }
        int nbr_edges() {
                return edge_count;
        }
        string get_nodes() {
                string stringOfNodes;
                for(char node: nodes)
                {
                        stringOfNodes.push_back(node);  //Generating string representation of the set of nodes 
                        stringOfNodes += ",";
                }
                stringOfNodes.pop_back();               //Popping the extra , appened at the end
                return stringOfNodes;
        }
        string get_edges() {
                string stringOfEdges;
                for(auto it: edges) {                   //Iterating through each entry of edges map [Key]
                        for(auto adj: it.second) {      //Iterating through the vector associated with each entry of the map [Value]
                                stringOfEdges += "[";
                                stringOfEdges.push_back(it.first);
                                stringOfEdges += ",";
                                stringOfEdges.push_back(adj);
                                stringOfEdges += "],";
                        }
                }
                stringOfEdges.pop_back();
                return stringOfEdges;
        }
        string to_s() {
                //Generating a string representation of the adjacency lists
                string adjacencyString;
                for(auto it: edges) {
                        adjacencyString.push_back(it.first);
                        adjacencyString += " -> ";
                        for(auto adj: it.second) {
                                adjacencyString.push_back(adj);
                                adjacencyString += ",";
                        }
                        adjacencyString.pop_back();
                        adjacencyString += "\n";
                }
                return adjacencyString;
        }
};

//Code for testing
int main() {
        Graph g = Graph();
        g.add_node('a');
        g.add_nodes({'b','c'});
        cout<<g.get_nodes()<<"\n";
        cout<<g.nbr_nodes()<<"\n";
        g.add_edge('a','b');
        g.add_edge('b','c');
        cout<<g.get_edges()<<"\n";
        cout<<g.nbr_edges()<<"\n";
        cout<<g.to_s();
}       
Know the answer?
Your Answer:

Post as a guest

Your Name:

What's your source?

Earn Coins

Coins can be redeemed for fabulous gifts.

Not the answer you're looking for?
Ask your own homework help question
Similar Questions
true/false An unweighted path length measures the number of edges in a graph. Breadth first search...
true/false An unweighted path length measures the number of edges in a graph. Breadth first search traverses the graph in "layers", beginning with the closest nodes to the ending location first. The computer knows about neighbors by checking the graph storage (such as the adjacency matrix or the adjacency list). Breadth first traversals use a stack to process nodes. The weighted path length is the sum of the edge costs on a path. Dijkstra's shortest path algorithm can be used...
Below is a list of edges in a directed graph with nodes A,B,C,D,E,F: B → E,...
Below is a list of edges in a directed graph with nodes A,B,C,D,E,F: B → E, B → F, C → D, D → A, E → F a) Find 5 topological sortings of the graph. b) Which edge must be removed in order to make ABCDEF to be a topological ordering?
# Problem Description Given a directed graph G = (V,E) with edge length l(e) > 0...
# Problem Description Given a directed graph G = (V,E) with edge length l(e) > 0 for any e in E, and a source vertex s. Use Dijkstra’s algorithm to calculate distance(s,v) for all of the vertices v in V. (You can implement your own priority queue or use the build-in function for C++/Python) # Input The graph has `n` vertices and `m` edges. There are m + 1 lines, the first line gives three numbers `n`,`m` and `s`(1 <=...
4. Each pair of adjacent nodes, or each pair of adjacent antinodes, is separated by a...
4. Each pair of adjacent nodes, or each pair of adjacent antinodes, is separated by a distance of a. µ b. L c. λ/2 d. λ 5. Convert µ = 2.56 x 10-3 g/cm to SI units. a. 2.56 x 102 kg/m b. 2.56 x 10-2 kg/m c. 2.56 x 10-3 kg/m d. 2.56 x 10-4 kg/m 6. During the experiment, you measure a length of (66.0 ± 2.0) cm for four useable loops of the standing wave. Solve for...
Let us consider Boruvka/Sollin's algorithm as shown . Note that Boruvka/Sollin algorithm selects several edges for...
Let us consider Boruvka/Sollin's algorithm as shown . Note that Boruvka/Sollin algorithm selects several edges for inclusion in T at each stage. It terminates when only one tree at the end of a stage or no edges to be selected. One Step of Boruvka/Sollin's Algorithm 1: Find minimum cost edge incident to every vertex. 2: Add to tree T. 3: Remove cycle if any. 4: Compress and clean graph (eliminate multiple edges). (a) Suppose that we run k phases of...
Assume that we are working with an aluminum alloy (k = 180 W/moC) triangular fin with...
Assume that we are working with an aluminum alloy (k = 180 W/moC) triangular fin with a length, L = 5 cm, base thickness, b = 1 cm, a very large width, w = 1 m. The base of the fin is maintained at a temperature of T0 = 200oC (at the left boundary node). The fin is losing heat to the surrounding air/medium at T? = 25oC with a heat transfer coefficient of h = 15 W/m2oC. Using the...
Helllp plz Allow the InsertAt method to add to the front position 0 (zero) also if...
Helllp plz Allow the InsertAt method to add to the front position 0 (zero) also if you try to add to a position greater than the number of nodes you get an error warning. /INSERT.C /*THIS PROGRAM READS A BINARY FILE (MUST ALREADY EXIST AND BE FILLED) */ /*AND PUTS IT INTO A LINKED LIST AND PRINTS THE LIST TO THE SCREEN) */ #include #include #include #include typedef struct ENTRY { char name[81]; }ENTRY; typedef struct LISTREC /* LISTREC is...
Homework Draw class diagrams for your HW4 - the Tetris Game shown below: Part 1: UML...
Homework Draw class diagrams for your HW4 - the Tetris Game shown below: Part 1: UML As a review, Here are some links to some explanations of UML diagrams if you need them. • https://courses.cs.washington.edu/courses/cse403/11sp/lectures/lecture08-uml1.pdf (Links to an external site.) • http://creately.com/blog/diagrams/class-diagram-relationships/ (Links to an external site.) • http://www.cs.bsu.edu/homepages/pvg/misc/uml/ (Links to an external site.) However you ended up creating the UML from HW4, your class diagram probably had some or all of these features: • Class variables: names, types, and...
ADVERTISEMENT
Need Online Homework Help?

Get Answers For Free
Most questions answered within 1 hours.

Ask a Question
ADVERTISEMENT