SlideShare a Scribd company logo
1 of 13
Download to read offline
Please finish the codes in Graph.h class.
#################### Vertex.h :
#ifndef VERTEX_H
#define VERTEX_H
#include
#include
#include
using namespace std;
class Vertex
{
private:
int _id;
static int _id_counter;
unordered_map _edges;
//cheater method for tracking path weight
int _path_weight = 0;
public:
Vertex()
{
_id_counter++;
_id = _id_counter;
}
Vertex(int id)
{
if (id >= _id_counter)
{
_id_counter = id + 1;
}
_id = id;
}
int getPathWeight() const
{
return _path_weight;
}
void setPathWeight(int weight)
{
_path_weight = weight;
}
int getId() const
{
return _id;
}
void addEdge(Vertex *vertex, int weight)
{
_edges[vertex] = weight;
}
int getEdgeWeight(Vertex *edge)
{
return _edges[edge];
}
unordered_map &getEdges()
{
return _edges;
}
void removeEdge(Vertex *vertex)
{
_edges.erase(vertex);
}
};
int operator==(const Vertex &lhs, const Vertex &rhs)
{
return lhs.getId() == rhs.getId();
}
bool operator<(const Vertex &lhs, const Vertex &rhs)
{
return lhs < rhs;
}
bool operator>(const Vertex &lhs, const Vertex &rhs)
{
return lhs > rhs;
}
class PathWeightComparer
{
public:
bool operator()(const Vertex lhs, const Vertex rhs)
{
return (lhs.getPathWeight() > rhs.getPathWeight());
}
};
//hashing algorithm must exist in STD namespace
namespace std {
template <>
struct hash
{
//provide a hash (convert grocery item into integer)
std::size_t operator()(const Vertex& item) const
{
size_t hash_val = 0;
//to hash INTs using the STL
hash int_hash{};
//define hashing algorithm. Ours is pretty easy...
hash_val = int_hash(item.getId());
//add others as necessary
return hash_val;
}
};
}
int Vertex::_id_counter = 0;
#endif
#################### Graph.h :
#ifndef GRAPH_H
#define GRAPH_H
#include
#include
#include
#include "Vertex.h"
using namespace std;
class Graph
{
unordered_map _vertices;
public:
void addVertex(Vertex vertex)
{
_vertices[vertex.getId()] = vertex;
}
//MA #12 TODO: IMPLEMENT!
unordered_map computeShortestPath(Vertex *start)
{
//holds known distances
unordered_map distances;
//underlying heap
priority_queue, PathWeightComparer> dijkstra_queue{};
//reset start's path weight
start->setPathWeight(0);
//make sure that the starting vertex is in the graph
//push on starting vertex
//while queue not empty
//Top of heap not known (in distances)?
//make known
//push on outgoing edges
return distances;
}
};
#endif
######################### main.cpp
#include
#include
#include
#include
#include "Graph.h"
#include "Vertex.h"
using namespace std;
void graphTest()
{
//populate graph
Graph graph{};
vector vertices{};
//generate vertices
for (int i = 0; i < 4; i++)
{
vertices.push_back(Vertex{});
}
/*
Graph: 0 -> 1 (weight 4)
0 -> 3 (weight 10)
1 -> 2 (weight 4)
1 -> 3 (weight 8)
2 -> 3 (weight 15)
*/
vertices[0].addEdge(&vertices[1], 4);
vertices[0].addEdge(&vertices[3], 20);
vertices[1].addEdge(&vertices[2], 4);
vertices[1].addEdge(&vertices[3], 8);
vertices[2].addEdge(&vertices[3], 15);
//add vertices to graph
for (auto vertex : vertices)
{
graph.addVertex(vertex);
}
unordered_map distances = graph.computeShortestPath(&vertices[0]);
cout << "Distance from 0 to 0: " << distances[vertices[0]] << " (expected: 0)" << endl;
cout << "Distance from 0 to 1: " << distances[vertices[1]] << " (expected: 4)" << endl;
cout << "Distance from 0 to 2: " << distances[vertices[2]] << " (expected: 8)" << endl;
cout << "Distance from 0 to 3: " << distances[vertices[3]] << " (expected: 12)" << endl;
}
int main(int argc, char* argv[])
{
graphTest();
}
Solution
Graph.h
// Includes
#include "Graph.h"
// Overloaders
int operator==(const vertex &lhs, const vertex &rhs)
{
return lhs.get_id() == rhs.get_id();
}
bool operator<(const vertex &lhs, const vertex &rhs)
{
return lhs.get_id() < rhs.get_id();
}
bool operator>(const vertex &lhs, const vertex &rhs)
{
return lhs.get_id() > rhs.get_id();
}
// Constructors
graph::graph()
{
//_vertices = empty!
}
graph::graph(unordered_map new_vertices)
{
_vertices = new_vertices;
}
// Copy Consturctor
// Destructor
// Getters
unordered_map graph::get_vertices() const
{
return _vertices;
}
// Setters
void graph::set_vertices(unordered_map new_vertices)
{
_vertices = new_vertices;
}
// Methods
unordered_map graph::computeShortestPath(vertex* start , int starting_vertex, int
ending_vertex)
{
//holds known distances
unordered_map paths;
//underlying heap
priority_queue, PathWeightComparer> dijkstra_queue{};
path temp;
//reset start's path weight
start->set_path_weight(0);
temp.push_vertex(start);
//make sure that the starting vertex is in the graph
if (_vertices.find(start->get_id()) != _vertices.end())
{
//push on starting vertex
dijkstra_queue.push(temp);
//while queue not empty
while (dijkstra_queue.empty() == false)
{
//push on outgoing edges that haven't been discovered
path top = dijkstra_queue.top();
dijkstra_queue.pop();
//Top of heap not known (in distances)?
if (paths.find(top.get_vertices().top()) == paths.end())
{
paths[top.get_vertices().top()] = top;
//push on outgoing edges
for (auto item : top.get_vertices().top()->get_edges())
{
vertex *next = item.first;
//not known? add to heap
if (paths.find(next) == paths.end())
{
path next_path = top;
int current_path_weight = item.second * next->get_load_factor();
next_path.push_vertex(next);
next_path.set_distance_traveled(top.get_distance_traveled() +
current_path_weight);
dijkstra_queue.push(next_path);
}
}
}
}
}
return paths;
}
Vertex.h
#ifndef VERTEX_H
#define VERTEX_H
#include
#include
#include
using namespace std;
class Vertex
{
private:
int _id;
static int _id_counter;
unordered_map _edges;
//unordered_map weight;
//cheater method for tracking path weight
int _path_weight = 0;
int loadfactor = 1;
public:
Vertex()
{
_id_counter++;
_id = _id_counter;
}
Vertex(int id)
{
if (id >= _id_counter)
{
_id_counter = id + 1;
}
_id = id;
}
int getPathWeight() const
{
return _path_weight;
}
void setPathWeight(int weight)
{
_path_weight = weight;
}
int getload() const
{
return loadfactor;
}
void setload(int weight)
{
loadfactor = weight;
}
void plusload()
{
loadfactor++;
}
void minusload()
{
loadfactor--;
}
int getId() const
{
return _id;
}
void setid(int id)
{
_id = id;
}
void addEdge(Vertex *vertex, int weight)
{
_edges[vertex] = weight;
}
int getEdgeWeight(Vertex *edge)
{
return _edges[edge];
}
unordered_map &getEdges()
{
return _edges;
}
void removeEdge(Vertex *vertex)
{
_edges.erase(vertex);
}
};
int operator==(const Vertex &lhs, const Vertex &rhs)
{
return lhs.getId() == rhs.getId();
}
bool operator<(const Vertex &lhs, const Vertex &rhs)
{
return lhs.getId() < rhs.getId();
}
bool operator>(const Vertex &lhs, const Vertex &rhs)
{
return lhs.getId() > rhs.getId();
}
class PathWeightComparer
{
public:
bool operator()(const Vertex lhs, const Vertex rhs)
{
return (lhs.getPathWeight() > rhs.getPathWeight());
}
};
//hashing algorithm must exist in STD namespace
namespace std {
template <>
struct hash
{
//provide a hash (convert grocery item into integer)
std::size_t operator()(const Vertex& item) const
{
size_t hash_val = 0;
//to hash INTs using the STL
hash int_hash{};
//define hashing algorithm. Ours is pretty easy...
hash_val = int_hash(item.getId());
//add others as necessary
return hash_val;
}
};
}
int Vertex::_id_counter = 0;
#endif
main.cpp
#include
#include
#include
#include
#include "Graph.h"
#include "Vertex.h"
using namespace std;
void graphTest()
{
//populate graph
Graph graph{};
vector vertices{};
//generate vertices
for (int i = 0; i < 4; i++)
{
vertices.push_back(Vertex{});
}
/*
Graph: 0 -> 1 (weight 4)
0 -> 3 (weight 10)
1 -> 2 (weight 4)
1 -> 3 (weight 8)
2 -> 3 (weight 15)
*/
vertices[0].addEdge(&vertices[1], 4);
vertices[0].addEdge(&vertices[3], 20);
vertices[1].addEdge(&vertices[2], 4);
vertices[1].addEdge(&vertices[3], 8);
vertices[2].addEdge(&vertices[3], 15);
//add vertices to graph
for (auto vertex : vertices)
{
graph.addVertex(vertex);
}
unordered_map distances = graph.computeShortestPath(&vertices[0]);
cout << "Distance from 0 to 0: " << distances[vertices[0]] << " (expected: 0)" << endl;
cout << "Distance from 0 to 1: " << distances[vertices[1]] << " (expected: 4)" << endl;
cout << "Distance from 0 to 2: " << distances[vertices[2]] << " (expected: 8)" << endl;
cout << "Distance from 0 to 3: " << distances[vertices[3]] << " (expected: 12)" << endl;
}
int main(int argc, char* argv[])
{
graphTest();
}

More Related Content

Similar to Please finish the codes in Graph.h class.#################### Vert.pdf

in this assignment you are asked to write a simple driver program an.pdf
in this assignment you are asked to write a simple driver program an.pdfin this assignment you are asked to write a simple driver program an.pdf
in this assignment you are asked to write a simple driver program an.pdfmichardsonkhaicarr37
 
Write a program that reads a connected graph from a file and displays.docx
 Write a program that reads a connected graph from a file and displays.docx Write a program that reads a connected graph from a file and displays.docx
Write a program that reads a connected graph from a file and displays.docxajoy21
 
Write CC++ a program that inputs a weighted undirected graph and fi.pdf
Write CC++ a program that inputs a weighted undirected graph and fi.pdfWrite CC++ a program that inputs a weighted undirected graph and fi.pdf
Write CC++ a program that inputs a weighted undirected graph and fi.pdf4babies2010
 
openFrameworks 007 - 3D
openFrameworks 007 - 3DopenFrameworks 007 - 3D
openFrameworks 007 - 3Droxlu
 
3장 자동적으로 움직이는 게임 에이전트 생성법_2
3장 자동적으로 움직이는 게임 에이전트 생성법_23장 자동적으로 움직이는 게임 에이전트 생성법_2
3장 자동적으로 움직이는 게임 에이전트 생성법_2suitzero
 
Im having trouble figuring out how to code these sections for an a.pdf
Im having trouble figuring out how to code these sections for an a.pdfIm having trouble figuring out how to code these sections for an a.pdf
Im having trouble figuring out how to code these sections for an a.pdfrishteygallery
 
Can you finish and write the int main for the code according to the in.pdf
Can you finish and write the int main for the code according to the in.pdfCan you finish and write the int main for the code according to the in.pdf
Can you finish and write the int main for the code according to the in.pdfaksachdevahosymills
 
A scrupulous code review - 15 bugs in C++ code
A scrupulous code review - 15 bugs in C++ codeA scrupulous code review - 15 bugs in C++ code
A scrupulous code review - 15 bugs in C++ codePVS-Studio LLC
 
The current program only run one iteration of the KMeans algorithm. .docx
The current program only run one iteration of the KMeans algorithm. .docxThe current program only run one iteration of the KMeans algorithm. .docx
The current program only run one iteration of the KMeans algorithm. .docxtodd241
 
Flashback, el primer malware masivo de sistemas Mac
Flashback, el primer malware masivo de sistemas MacFlashback, el primer malware masivo de sistemas Mac
Flashback, el primer malware masivo de sistemas MacESET Latinoamérica
 
Given the following codepackage data1;import java.util.;p.pdf
Given the following codepackage data1;import java.util.;p.pdfGiven the following codepackage data1;import java.util.;p.pdf
Given the following codepackage data1;import java.util.;p.pdfillyasraja7
 
Please implement in Java. comments would be appreciated 5.pdf
Please implement in Java. comments would be appreciated 5.pdfPlease implement in Java. comments would be appreciated 5.pdf
Please implement in Java. comments would be appreciated 5.pdffms12345
 
check the modifed code now you will get all operations done.termin.pdf
check the modifed code now you will get all operations done.termin.pdfcheck the modifed code now you will get all operations done.termin.pdf
check the modifed code now you will get all operations done.termin.pdfangelfragranc
 
Aodv routing protocol code in ns2
Aodv routing protocol code in ns2Aodv routing protocol code in ns2
Aodv routing protocol code in ns2Prof Ansari
 
a) Write the recursive function in C++ to sort a set of data using M.pdf
a) Write the recursive function in C++ to sort a set of data using M.pdfa) Write the recursive function in C++ to sort a set of data using M.pdf
a) Write the recursive function in C++ to sort a set of data using M.pdfnageswara1958
 
Questions has 4 parts.1st part Program to implement sorting algor.pdf
Questions has 4 parts.1st part Program to implement sorting algor.pdfQuestions has 4 parts.1st part Program to implement sorting algor.pdf
Questions has 4 parts.1st part Program to implement sorting algor.pdfapexelectronices01
 
package chapter15;import javafx.application.Application;import j.pdf
package chapter15;import javafx.application.Application;import j.pdfpackage chapter15;import javafx.application.Application;import j.pdf
package chapter15;import javafx.application.Application;import j.pdfKARTIKINDIA
 

Similar to Please finish the codes in Graph.h class.#################### Vert.pdf (20)

in this assignment you are asked to write a simple driver program an.pdf
in this assignment you are asked to write a simple driver program an.pdfin this assignment you are asked to write a simple driver program an.pdf
in this assignment you are asked to write a simple driver program an.pdf
 
Write a program that reads a connected graph from a file and displays.docx
 Write a program that reads a connected graph from a file and displays.docx Write a program that reads a connected graph from a file and displays.docx
Write a program that reads a connected graph from a file and displays.docx
 
Write CC++ a program that inputs a weighted undirected graph and fi.pdf
Write CC++ a program that inputs a weighted undirected graph and fi.pdfWrite CC++ a program that inputs a weighted undirected graph and fi.pdf
Write CC++ a program that inputs a weighted undirected graph and fi.pdf
 
openFrameworks 007 - 3D
openFrameworks 007 - 3DopenFrameworks 007 - 3D
openFrameworks 007 - 3D
 
3장 자동적으로 움직이는 게임 에이전트 생성법_2
3장 자동적으로 움직이는 게임 에이전트 생성법_23장 자동적으로 움직이는 게임 에이전트 생성법_2
3장 자동적으로 움직이는 게임 에이전트 생성법_2
 
Im having trouble figuring out how to code these sections for an a.pdf
Im having trouble figuring out how to code these sections for an a.pdfIm having trouble figuring out how to code these sections for an a.pdf
Im having trouble figuring out how to code these sections for an a.pdf
 
Can you finish and write the int main for the code according to the in.pdf
Can you finish and write the int main for the code according to the in.pdfCan you finish and write the int main for the code according to the in.pdf
Can you finish and write the int main for the code according to the in.pdf
 
A scrupulous code review - 15 bugs in C++ code
A scrupulous code review - 15 bugs in C++ codeA scrupulous code review - 15 bugs in C++ code
A scrupulous code review - 15 bugs in C++ code
 
The current program only run one iteration of the KMeans algorithm. .docx
The current program only run one iteration of the KMeans algorithm. .docxThe current program only run one iteration of the KMeans algorithm. .docx
The current program only run one iteration of the KMeans algorithm. .docx
 
12
1212
12
 
Flashback, el primer malware masivo de sistemas Mac
Flashback, el primer malware masivo de sistemas MacFlashback, el primer malware masivo de sistemas Mac
Flashback, el primer malware masivo de sistemas Mac
 
C++ programs
C++ programsC++ programs
C++ programs
 
Given the following codepackage data1;import java.util.;p.pdf
Given the following codepackage data1;import java.util.;p.pdfGiven the following codepackage data1;import java.util.;p.pdf
Given the following codepackage data1;import java.util.;p.pdf
 
Please implement in Java. comments would be appreciated 5.pdf
Please implement in Java. comments would be appreciated 5.pdfPlease implement in Java. comments would be appreciated 5.pdf
Please implement in Java. comments would be appreciated 5.pdf
 
check the modifed code now you will get all operations done.termin.pdf
check the modifed code now you will get all operations done.termin.pdfcheck the modifed code now you will get all operations done.termin.pdf
check the modifed code now you will get all operations done.termin.pdf
 
Aodv routing protocol code in ns2
Aodv routing protocol code in ns2Aodv routing protocol code in ns2
Aodv routing protocol code in ns2
 
a) Write the recursive function in C++ to sort a set of data using M.pdf
a) Write the recursive function in C++ to sort a set of data using M.pdfa) Write the recursive function in C++ to sort a set of data using M.pdf
a) Write the recursive function in C++ to sort a set of data using M.pdf
 
2 a networkflow
2 a networkflow2 a networkflow
2 a networkflow
 
Questions has 4 parts.1st part Program to implement sorting algor.pdf
Questions has 4 parts.1st part Program to implement sorting algor.pdfQuestions has 4 parts.1st part Program to implement sorting algor.pdf
Questions has 4 parts.1st part Program to implement sorting algor.pdf
 
package chapter15;import javafx.application.Application;import j.pdf
package chapter15;import javafx.application.Application;import j.pdfpackage chapter15;import javafx.application.Application;import j.pdf
package chapter15;import javafx.application.Application;import j.pdf
 

More from petercoiffeur18

John, a sociologist, will be focusing on how larger societal institu.pdf
John, a sociologist, will be focusing on how larger societal institu.pdfJohn, a sociologist, will be focusing on how larger societal institu.pdf
John, a sociologist, will be focusing on how larger societal institu.pdfpetercoiffeur18
 
Implement the ListArray ADT-Implement the following operations.pdf
Implement the ListArray ADT-Implement the following operations.pdfImplement the ListArray ADT-Implement the following operations.pdf
Implement the ListArray ADT-Implement the following operations.pdfpetercoiffeur18
 
In what ways do humans effect the environment Explain in 200 words.pdf
In what ways do humans effect the environment Explain in 200 words.pdfIn what ways do humans effect the environment Explain in 200 words.pdf
In what ways do humans effect the environment Explain in 200 words.pdfpetercoiffeur18
 
i need a taking turn method for a player vs computer battleship game.pdf
i need a taking turn method for a player vs computer battleship game.pdfi need a taking turn method for a player vs computer battleship game.pdf
i need a taking turn method for a player vs computer battleship game.pdfpetercoiffeur18
 
I am trying to change this code from STRUCTS to CLASSES, the members.pdf
I am trying to change this code from STRUCTS to CLASSES, the members.pdfI am trying to change this code from STRUCTS to CLASSES, the members.pdf
I am trying to change this code from STRUCTS to CLASSES, the members.pdfpetercoiffeur18
 
how internal resources and capabilities can be a source of sustainab.pdf
how internal resources and capabilities can be a source of sustainab.pdfhow internal resources and capabilities can be a source of sustainab.pdf
how internal resources and capabilities can be a source of sustainab.pdfpetercoiffeur18
 
For an organism that is growing using glucose as the electron donor, .pdf
For an organism that is growing using glucose as the electron donor, .pdfFor an organism that is growing using glucose as the electron donor, .pdf
For an organism that is growing using glucose as the electron donor, .pdfpetercoiffeur18
 
Exercise 5.6.28. For each of the following descriptions of a function.pdf
Exercise 5.6.28. For each of the following descriptions of a function.pdfExercise 5.6.28. For each of the following descriptions of a function.pdf
Exercise 5.6.28. For each of the following descriptions of a function.pdfpetercoiffeur18
 
Discuss concepts associated with mercantilism demonstrating key poli.pdf
Discuss concepts associated with mercantilism demonstrating key poli.pdfDiscuss concepts associated with mercantilism demonstrating key poli.pdf
Discuss concepts associated with mercantilism demonstrating key poli.pdfpetercoiffeur18
 
C++ Caesar Cipher project. Write your codes for the following functi.pdf
C++ Caesar Cipher project. Write your codes for the following functi.pdfC++ Caesar Cipher project. Write your codes for the following functi.pdf
C++ Caesar Cipher project. Write your codes for the following functi.pdfpetercoiffeur18
 
any idea#includeiostream using stdcout; using stdendl; .pdf
any idea#includeiostream using stdcout; using stdendl; .pdfany idea#includeiostream using stdcout; using stdendl; .pdf
any idea#includeiostream using stdcout; using stdendl; .pdfpetercoiffeur18
 
a) Use Newton’s Polynomials for Evenly Spaced data to derive the O(h.pdf
a) Use Newton’s Polynomials for Evenly Spaced data to derive the O(h.pdfa) Use Newton’s Polynomials for Evenly Spaced data to derive the O(h.pdf
a) Use Newton’s Polynomials for Evenly Spaced data to derive the O(h.pdfpetercoiffeur18
 
A radio station has a power output of 200 watts. What is the intensit.pdf
A radio station has a power output of 200 watts. What is the intensit.pdfA radio station has a power output of 200 watts. What is the intensit.pdf
A radio station has a power output of 200 watts. What is the intensit.pdfpetercoiffeur18
 
21) What are the fundamental particles of lepton and quarks How man.pdf
21) What are the fundamental particles of lepton and quarks How man.pdf21) What are the fundamental particles of lepton and quarks How man.pdf
21) What are the fundamental particles of lepton and quarks How man.pdfpetercoiffeur18
 
Case 1-A Transition to SupervisorTristan came in on the ground fl.pdf
Case 1-A Transition to SupervisorTristan came in on the ground fl.pdfCase 1-A Transition to SupervisorTristan came in on the ground fl.pdf
Case 1-A Transition to SupervisorTristan came in on the ground fl.pdfpetercoiffeur18
 
x , y Midterm Exsm-201840x Exam C httpsbb-montgomerycollege.blac.pdf
x , y Midterm Exsm-201840x Exam C httpsbb-montgomerycollege.blac.pdfx , y Midterm Exsm-201840x Exam C httpsbb-montgomerycollege.blac.pdf
x , y Midterm Exsm-201840x Exam C httpsbb-montgomerycollege.blac.pdfpetercoiffeur18
 
Why would a cell want to express genes in an operon Why notSol.pdf
Why would a cell want to express genes in an operon Why notSol.pdfWhy would a cell want to express genes in an operon Why notSol.pdf
Why would a cell want to express genes in an operon Why notSol.pdfpetercoiffeur18
 
When discussing the epidemiology of virus infections, the CDC often .pdf
When discussing the epidemiology of virus infections, the CDC often .pdfWhen discussing the epidemiology of virus infections, the CDC often .pdf
When discussing the epidemiology of virus infections, the CDC often .pdfpetercoiffeur18
 
What relationship is there between gobalization and development.pdf
What relationship is there between gobalization and development.pdfWhat relationship is there between gobalization and development.pdf
What relationship is there between gobalization and development.pdfpetercoiffeur18
 
what is the number between 4.5 and 4.75 on the number linew.pdf
what is the number between 4.5 and 4.75 on the number linew.pdfwhat is the number between 4.5 and 4.75 on the number linew.pdf
what is the number between 4.5 and 4.75 on the number linew.pdfpetercoiffeur18
 

More from petercoiffeur18 (20)

John, a sociologist, will be focusing on how larger societal institu.pdf
John, a sociologist, will be focusing on how larger societal institu.pdfJohn, a sociologist, will be focusing on how larger societal institu.pdf
John, a sociologist, will be focusing on how larger societal institu.pdf
 
Implement the ListArray ADT-Implement the following operations.pdf
Implement the ListArray ADT-Implement the following operations.pdfImplement the ListArray ADT-Implement the following operations.pdf
Implement the ListArray ADT-Implement the following operations.pdf
 
In what ways do humans effect the environment Explain in 200 words.pdf
In what ways do humans effect the environment Explain in 200 words.pdfIn what ways do humans effect the environment Explain in 200 words.pdf
In what ways do humans effect the environment Explain in 200 words.pdf
 
i need a taking turn method for a player vs computer battleship game.pdf
i need a taking turn method for a player vs computer battleship game.pdfi need a taking turn method for a player vs computer battleship game.pdf
i need a taking turn method for a player vs computer battleship game.pdf
 
I am trying to change this code from STRUCTS to CLASSES, the members.pdf
I am trying to change this code from STRUCTS to CLASSES, the members.pdfI am trying to change this code from STRUCTS to CLASSES, the members.pdf
I am trying to change this code from STRUCTS to CLASSES, the members.pdf
 
how internal resources and capabilities can be a source of sustainab.pdf
how internal resources and capabilities can be a source of sustainab.pdfhow internal resources and capabilities can be a source of sustainab.pdf
how internal resources and capabilities can be a source of sustainab.pdf
 
For an organism that is growing using glucose as the electron donor, .pdf
For an organism that is growing using glucose as the electron donor, .pdfFor an organism that is growing using glucose as the electron donor, .pdf
For an organism that is growing using glucose as the electron donor, .pdf
 
Exercise 5.6.28. For each of the following descriptions of a function.pdf
Exercise 5.6.28. For each of the following descriptions of a function.pdfExercise 5.6.28. For each of the following descriptions of a function.pdf
Exercise 5.6.28. For each of the following descriptions of a function.pdf
 
Discuss concepts associated with mercantilism demonstrating key poli.pdf
Discuss concepts associated with mercantilism demonstrating key poli.pdfDiscuss concepts associated with mercantilism demonstrating key poli.pdf
Discuss concepts associated with mercantilism demonstrating key poli.pdf
 
C++ Caesar Cipher project. Write your codes for the following functi.pdf
C++ Caesar Cipher project. Write your codes for the following functi.pdfC++ Caesar Cipher project. Write your codes for the following functi.pdf
C++ Caesar Cipher project. Write your codes for the following functi.pdf
 
any idea#includeiostream using stdcout; using stdendl; .pdf
any idea#includeiostream using stdcout; using stdendl; .pdfany idea#includeiostream using stdcout; using stdendl; .pdf
any idea#includeiostream using stdcout; using stdendl; .pdf
 
a) Use Newton’s Polynomials for Evenly Spaced data to derive the O(h.pdf
a) Use Newton’s Polynomials for Evenly Spaced data to derive the O(h.pdfa) Use Newton’s Polynomials for Evenly Spaced data to derive the O(h.pdf
a) Use Newton’s Polynomials for Evenly Spaced data to derive the O(h.pdf
 
A radio station has a power output of 200 watts. What is the intensit.pdf
A radio station has a power output of 200 watts. What is the intensit.pdfA radio station has a power output of 200 watts. What is the intensit.pdf
A radio station has a power output of 200 watts. What is the intensit.pdf
 
21) What are the fundamental particles of lepton and quarks How man.pdf
21) What are the fundamental particles of lepton and quarks How man.pdf21) What are the fundamental particles of lepton and quarks How man.pdf
21) What are the fundamental particles of lepton and quarks How man.pdf
 
Case 1-A Transition to SupervisorTristan came in on the ground fl.pdf
Case 1-A Transition to SupervisorTristan came in on the ground fl.pdfCase 1-A Transition to SupervisorTristan came in on the ground fl.pdf
Case 1-A Transition to SupervisorTristan came in on the ground fl.pdf
 
x , y Midterm Exsm-201840x Exam C httpsbb-montgomerycollege.blac.pdf
x , y Midterm Exsm-201840x Exam C httpsbb-montgomerycollege.blac.pdfx , y Midterm Exsm-201840x Exam C httpsbb-montgomerycollege.blac.pdf
x , y Midterm Exsm-201840x Exam C httpsbb-montgomerycollege.blac.pdf
 
Why would a cell want to express genes in an operon Why notSol.pdf
Why would a cell want to express genes in an operon Why notSol.pdfWhy would a cell want to express genes in an operon Why notSol.pdf
Why would a cell want to express genes in an operon Why notSol.pdf
 
When discussing the epidemiology of virus infections, the CDC often .pdf
When discussing the epidemiology of virus infections, the CDC often .pdfWhen discussing the epidemiology of virus infections, the CDC often .pdf
When discussing the epidemiology of virus infections, the CDC often .pdf
 
What relationship is there between gobalization and development.pdf
What relationship is there between gobalization and development.pdfWhat relationship is there between gobalization and development.pdf
What relationship is there between gobalization and development.pdf
 
what is the number between 4.5 and 4.75 on the number linew.pdf
what is the number between 4.5 and 4.75 on the number linew.pdfwhat is the number between 4.5 and 4.75 on the number linew.pdf
what is the number between 4.5 and 4.75 on the number linew.pdf
 

Recently uploaded

Paris 2024 Olympic Geographies - an activity
Paris 2024 Olympic Geographies - an activityParis 2024 Olympic Geographies - an activity
Paris 2024 Olympic Geographies - an activityGeoBlogs
 
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...Krashi Coaching
 
BASLIQ CURRENT LOOKBOOK LOOKBOOK(1) (1).pdf
BASLIQ CURRENT LOOKBOOK  LOOKBOOK(1) (1).pdfBASLIQ CURRENT LOOKBOOK  LOOKBOOK(1) (1).pdf
BASLIQ CURRENT LOOKBOOK LOOKBOOK(1) (1).pdfSoniaTolstoy
 
Final demo Grade 9 for demo Plan dessert.pptx
Final demo Grade 9 for demo Plan dessert.pptxFinal demo Grade 9 for demo Plan dessert.pptx
Final demo Grade 9 for demo Plan dessert.pptxAvyJaneVismanos
 
A Critique of the Proposed National Education Policy Reform
A Critique of the Proposed National Education Policy ReformA Critique of the Proposed National Education Policy Reform
A Critique of the Proposed National Education Policy ReformChameera Dedduwage
 
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️9953056974 Low Rate Call Girls In Saket, Delhi NCR
 
ECONOMIC CONTEXT - LONG FORM TV DRAMA - PPT
ECONOMIC CONTEXT - LONG FORM TV DRAMA - PPTECONOMIC CONTEXT - LONG FORM TV DRAMA - PPT
ECONOMIC CONTEXT - LONG FORM TV DRAMA - PPTiammrhaywood
 
Blooming Together_ Growing a Community Garden Worksheet.docx
Blooming Together_ Growing a Community Garden Worksheet.docxBlooming Together_ Growing a Community Garden Worksheet.docx
Blooming Together_ Growing a Community Garden Worksheet.docxUnboundStockton
 
Employee wellbeing at the workplace.pptx
Employee wellbeing at the workplace.pptxEmployee wellbeing at the workplace.pptx
Employee wellbeing at the workplace.pptxNirmalaLoungPoorunde1
 
EPANDING THE CONTENT OF AN OUTLINE using notes.pptx
EPANDING THE CONTENT OF AN OUTLINE using notes.pptxEPANDING THE CONTENT OF AN OUTLINE using notes.pptx
EPANDING THE CONTENT OF AN OUTLINE using notes.pptxRaymartEstabillo3
 
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptxSOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptxiammrhaywood
 
Pharmacognosy Flower 3. Compositae 2023.pdf
Pharmacognosy Flower 3. Compositae 2023.pdfPharmacognosy Flower 3. Compositae 2023.pdf
Pharmacognosy Flower 3. Compositae 2023.pdfMahmoud M. Sallam
 
Proudly South Africa powerpoint Thorisha.pptx
Proudly South Africa powerpoint Thorisha.pptxProudly South Africa powerpoint Thorisha.pptx
Proudly South Africa powerpoint Thorisha.pptxthorishapillay1
 
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptx
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptxPOINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptx
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptxSayali Powar
 
History Class XII Ch. 3 Kinship, Caste and Class (1).pptx
History Class XII Ch. 3 Kinship, Caste and Class (1).pptxHistory Class XII Ch. 3 Kinship, Caste and Class (1).pptx
History Class XII Ch. 3 Kinship, Caste and Class (1).pptxsocialsciencegdgrohi
 
Organic Name Reactions for the students and aspirants of Chemistry12th.pptx
Organic Name Reactions  for the students and aspirants of Chemistry12th.pptxOrganic Name Reactions  for the students and aspirants of Chemistry12th.pptx
Organic Name Reactions for the students and aspirants of Chemistry12th.pptxVS Mahajan Coaching Centre
 

Recently uploaded (20)

Paris 2024 Olympic Geographies - an activity
Paris 2024 Olympic Geographies - an activityParis 2024 Olympic Geographies - an activity
Paris 2024 Olympic Geographies - an activity
 
TataKelola dan KamSiber Kecerdasan Buatan v022.pdf
TataKelola dan KamSiber Kecerdasan Buatan v022.pdfTataKelola dan KamSiber Kecerdasan Buatan v022.pdf
TataKelola dan KamSiber Kecerdasan Buatan v022.pdf
 
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...
 
BASLIQ CURRENT LOOKBOOK LOOKBOOK(1) (1).pdf
BASLIQ CURRENT LOOKBOOK  LOOKBOOK(1) (1).pdfBASLIQ CURRENT LOOKBOOK  LOOKBOOK(1) (1).pdf
BASLIQ CURRENT LOOKBOOK LOOKBOOK(1) (1).pdf
 
Final demo Grade 9 for demo Plan dessert.pptx
Final demo Grade 9 for demo Plan dessert.pptxFinal demo Grade 9 for demo Plan dessert.pptx
Final demo Grade 9 for demo Plan dessert.pptx
 
A Critique of the Proposed National Education Policy Reform
A Critique of the Proposed National Education Policy ReformA Critique of the Proposed National Education Policy Reform
A Critique of the Proposed National Education Policy Reform
 
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️
 
Model Call Girl in Tilak Nagar Delhi reach out to us at 🔝9953056974🔝
Model Call Girl in Tilak Nagar Delhi reach out to us at 🔝9953056974🔝Model Call Girl in Tilak Nagar Delhi reach out to us at 🔝9953056974🔝
Model Call Girl in Tilak Nagar Delhi reach out to us at 🔝9953056974🔝
 
ECONOMIC CONTEXT - LONG FORM TV DRAMA - PPT
ECONOMIC CONTEXT - LONG FORM TV DRAMA - PPTECONOMIC CONTEXT - LONG FORM TV DRAMA - PPT
ECONOMIC CONTEXT - LONG FORM TV DRAMA - PPT
 
Blooming Together_ Growing a Community Garden Worksheet.docx
Blooming Together_ Growing a Community Garden Worksheet.docxBlooming Together_ Growing a Community Garden Worksheet.docx
Blooming Together_ Growing a Community Garden Worksheet.docx
 
Employee wellbeing at the workplace.pptx
Employee wellbeing at the workplace.pptxEmployee wellbeing at the workplace.pptx
Employee wellbeing at the workplace.pptx
 
EPANDING THE CONTENT OF AN OUTLINE using notes.pptx
EPANDING THE CONTENT OF AN OUTLINE using notes.pptxEPANDING THE CONTENT OF AN OUTLINE using notes.pptx
EPANDING THE CONTENT OF AN OUTLINE using notes.pptx
 
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptxSOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
 
Staff of Color (SOC) Retention Efforts DDSD
Staff of Color (SOC) Retention Efforts DDSDStaff of Color (SOC) Retention Efforts DDSD
Staff of Color (SOC) Retention Efforts DDSD
 
Model Call Girl in Bikash Puri Delhi reach out to us at 🔝9953056974🔝
Model Call Girl in Bikash Puri  Delhi reach out to us at 🔝9953056974🔝Model Call Girl in Bikash Puri  Delhi reach out to us at 🔝9953056974🔝
Model Call Girl in Bikash Puri Delhi reach out to us at 🔝9953056974🔝
 
Pharmacognosy Flower 3. Compositae 2023.pdf
Pharmacognosy Flower 3. Compositae 2023.pdfPharmacognosy Flower 3. Compositae 2023.pdf
Pharmacognosy Flower 3. Compositae 2023.pdf
 
Proudly South Africa powerpoint Thorisha.pptx
Proudly South Africa powerpoint Thorisha.pptxProudly South Africa powerpoint Thorisha.pptx
Proudly South Africa powerpoint Thorisha.pptx
 
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptx
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptxPOINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptx
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptx
 
History Class XII Ch. 3 Kinship, Caste and Class (1).pptx
History Class XII Ch. 3 Kinship, Caste and Class (1).pptxHistory Class XII Ch. 3 Kinship, Caste and Class (1).pptx
History Class XII Ch. 3 Kinship, Caste and Class (1).pptx
 
Organic Name Reactions for the students and aspirants of Chemistry12th.pptx
Organic Name Reactions  for the students and aspirants of Chemistry12th.pptxOrganic Name Reactions  for the students and aspirants of Chemistry12th.pptx
Organic Name Reactions for the students and aspirants of Chemistry12th.pptx
 

Please finish the codes in Graph.h class.#################### Vert.pdf

  • 1. Please finish the codes in Graph.h class. #################### Vertex.h : #ifndef VERTEX_H #define VERTEX_H #include #include #include using namespace std; class Vertex { private: int _id; static int _id_counter; unordered_map _edges; //cheater method for tracking path weight int _path_weight = 0; public: Vertex() { _id_counter++; _id = _id_counter; } Vertex(int id) { if (id >= _id_counter) { _id_counter = id + 1; } _id = id; } int getPathWeight() const { return _path_weight; } void setPathWeight(int weight)
  • 2. { _path_weight = weight; } int getId() const { return _id; } void addEdge(Vertex *vertex, int weight) { _edges[vertex] = weight; } int getEdgeWeight(Vertex *edge) { return _edges[edge]; } unordered_map &getEdges() { return _edges; } void removeEdge(Vertex *vertex) { _edges.erase(vertex); } }; int operator==(const Vertex &lhs, const Vertex &rhs) { return lhs.getId() == rhs.getId(); } bool operator<(const Vertex &lhs, const Vertex &rhs) { return lhs < rhs; } bool operator>(const Vertex &lhs, const Vertex &rhs) { return lhs > rhs; }
  • 3. class PathWeightComparer { public: bool operator()(const Vertex lhs, const Vertex rhs) { return (lhs.getPathWeight() > rhs.getPathWeight()); } }; //hashing algorithm must exist in STD namespace namespace std { template <> struct hash { //provide a hash (convert grocery item into integer) std::size_t operator()(const Vertex& item) const { size_t hash_val = 0; //to hash INTs using the STL hash int_hash{}; //define hashing algorithm. Ours is pretty easy... hash_val = int_hash(item.getId()); //add others as necessary return hash_val; } }; } int Vertex::_id_counter = 0; #endif #################### Graph.h : #ifndef GRAPH_H #define GRAPH_H #include #include #include #include "Vertex.h"
  • 4. using namespace std; class Graph { unordered_map _vertices; public: void addVertex(Vertex vertex) { _vertices[vertex.getId()] = vertex; } //MA #12 TODO: IMPLEMENT! unordered_map computeShortestPath(Vertex *start) { //holds known distances unordered_map distances; //underlying heap priority_queue, PathWeightComparer> dijkstra_queue{}; //reset start's path weight start->setPathWeight(0); //make sure that the starting vertex is in the graph //push on starting vertex //while queue not empty //Top of heap not known (in distances)? //make known //push on outgoing edges return distances; } }; #endif ######################### main.cpp #include #include
  • 5. #include #include #include "Graph.h" #include "Vertex.h" using namespace std; void graphTest() { //populate graph Graph graph{}; vector vertices{}; //generate vertices for (int i = 0; i < 4; i++) { vertices.push_back(Vertex{}); } /* Graph: 0 -> 1 (weight 4) 0 -> 3 (weight 10) 1 -> 2 (weight 4) 1 -> 3 (weight 8) 2 -> 3 (weight 15) */ vertices[0].addEdge(&vertices[1], 4); vertices[0].addEdge(&vertices[3], 20); vertices[1].addEdge(&vertices[2], 4); vertices[1].addEdge(&vertices[3], 8); vertices[2].addEdge(&vertices[3], 15); //add vertices to graph for (auto vertex : vertices) { graph.addVertex(vertex); } unordered_map distances = graph.computeShortestPath(&vertices[0]); cout << "Distance from 0 to 0: " << distances[vertices[0]] << " (expected: 0)" << endl; cout << "Distance from 0 to 1: " << distances[vertices[1]] << " (expected: 4)" << endl;
  • 6. cout << "Distance from 0 to 2: " << distances[vertices[2]] << " (expected: 8)" << endl; cout << "Distance from 0 to 3: " << distances[vertices[3]] << " (expected: 12)" << endl; } int main(int argc, char* argv[]) { graphTest(); } Solution Graph.h // Includes #include "Graph.h" // Overloaders int operator==(const vertex &lhs, const vertex &rhs) { return lhs.get_id() == rhs.get_id(); } bool operator<(const vertex &lhs, const vertex &rhs) { return lhs.get_id() < rhs.get_id(); } bool operator>(const vertex &lhs, const vertex &rhs) { return lhs.get_id() > rhs.get_id(); } // Constructors graph::graph() { //_vertices = empty! } graph::graph(unordered_map new_vertices) { _vertices = new_vertices;
  • 7. } // Copy Consturctor // Destructor // Getters unordered_map graph::get_vertices() const { return _vertices; } // Setters void graph::set_vertices(unordered_map new_vertices) { _vertices = new_vertices; } // Methods unordered_map graph::computeShortestPath(vertex* start , int starting_vertex, int ending_vertex) { //holds known distances unordered_map paths; //underlying heap priority_queue, PathWeightComparer> dijkstra_queue{}; path temp; //reset start's path weight start->set_path_weight(0); temp.push_vertex(start); //make sure that the starting vertex is in the graph if (_vertices.find(start->get_id()) != _vertices.end()) { //push on starting vertex dijkstra_queue.push(temp); //while queue not empty while (dijkstra_queue.empty() == false) { //push on outgoing edges that haven't been discovered
  • 8. path top = dijkstra_queue.top(); dijkstra_queue.pop(); //Top of heap not known (in distances)? if (paths.find(top.get_vertices().top()) == paths.end()) { paths[top.get_vertices().top()] = top; //push on outgoing edges for (auto item : top.get_vertices().top()->get_edges()) { vertex *next = item.first; //not known? add to heap if (paths.find(next) == paths.end()) { path next_path = top; int current_path_weight = item.second * next->get_load_factor(); next_path.push_vertex(next); next_path.set_distance_traveled(top.get_distance_traveled() + current_path_weight); dijkstra_queue.push(next_path); } } } } } return paths; } Vertex.h #ifndef VERTEX_H #define VERTEX_H #include #include #include
  • 9. using namespace std; class Vertex { private: int _id; static int _id_counter; unordered_map _edges; //unordered_map weight; //cheater method for tracking path weight int _path_weight = 0; int loadfactor = 1; public: Vertex() { _id_counter++; _id = _id_counter; } Vertex(int id) { if (id >= _id_counter) { _id_counter = id + 1; } _id = id; } int getPathWeight() const { return _path_weight; } void setPathWeight(int weight) { _path_weight = weight; } int getload() const {
  • 10. return loadfactor; } void setload(int weight) { loadfactor = weight; } void plusload() { loadfactor++; } void minusload() { loadfactor--; } int getId() const { return _id; } void setid(int id) { _id = id; } void addEdge(Vertex *vertex, int weight) { _edges[vertex] = weight; } int getEdgeWeight(Vertex *edge) { return _edges[edge]; } unordered_map &getEdges() { return _edges; } void removeEdge(Vertex *vertex) {
  • 11. _edges.erase(vertex); } }; int operator==(const Vertex &lhs, const Vertex &rhs) { return lhs.getId() == rhs.getId(); } bool operator<(const Vertex &lhs, const Vertex &rhs) { return lhs.getId() < rhs.getId(); } bool operator>(const Vertex &lhs, const Vertex &rhs) { return lhs.getId() > rhs.getId(); } class PathWeightComparer { public: bool operator()(const Vertex lhs, const Vertex rhs) { return (lhs.getPathWeight() > rhs.getPathWeight()); } }; //hashing algorithm must exist in STD namespace namespace std { template <> struct hash { //provide a hash (convert grocery item into integer) std::size_t operator()(const Vertex& item) const { size_t hash_val = 0; //to hash INTs using the STL hash int_hash{}; //define hashing algorithm. Ours is pretty easy... hash_val = int_hash(item.getId());
  • 12. //add others as necessary return hash_val; } }; } int Vertex::_id_counter = 0; #endif main.cpp #include #include #include #include #include "Graph.h" #include "Vertex.h" using namespace std; void graphTest() { //populate graph Graph graph{}; vector vertices{}; //generate vertices for (int i = 0; i < 4; i++) { vertices.push_back(Vertex{}); } /* Graph: 0 -> 1 (weight 4) 0 -> 3 (weight 10) 1 -> 2 (weight 4) 1 -> 3 (weight 8) 2 -> 3 (weight 15) */
  • 13. vertices[0].addEdge(&vertices[1], 4); vertices[0].addEdge(&vertices[3], 20); vertices[1].addEdge(&vertices[2], 4); vertices[1].addEdge(&vertices[3], 8); vertices[2].addEdge(&vertices[3], 15); //add vertices to graph for (auto vertex : vertices) { graph.addVertex(vertex); } unordered_map distances = graph.computeShortestPath(&vertices[0]); cout << "Distance from 0 to 0: " << distances[vertices[0]] << " (expected: 0)" << endl; cout << "Distance from 0 to 1: " << distances[vertices[1]] << " (expected: 4)" << endl; cout << "Distance from 0 to 2: " << distances[vertices[2]] << " (expected: 8)" << endl; cout << "Distance from 0 to 3: " << distances[vertices[3]] << " (expected: 12)" << endl; } int main(int argc, char* argv[]) { graphTest(); }