Skip to content

Instantly share code, notes, and snippets.

@YaoC
Created January 15, 2017 18:51
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save YaoC/641c23824a9d01bc852f6e0aeb9fe4dd to your computer and use it in GitHub Desktop.
Save YaoC/641c23824a9d01bc852f6e0aeb9fe4dd to your computer and use it in GitHub Desktop.
#include <string>
#include <iostream>
#include <fstream>
#include <sstream>
#include <vector>
#include "ics46goody.hpp"
#include "array_queue.hpp"
#include "array_priority_queue.hpp"
#include "array_set.hpp"
#include "array_map.hpp"
typedef ics::ArraySet<std::string> NodeSet;
typedef ics::pair<std::string,NodeSet> GraphEntry;
bool graph_entry_gt (const GraphEntry& a, const GraphEntry& b)
{return a.first<b.first;}
typedef ics::ArrayPriorityQueue<GraphEntry,graph_entry_gt> GraphPQ;
typedef ics::ArrayMap<std::string,NodeSet> Graph;
//Read an open file of edges (node names separated by semicolons, with an
// edge going from the first node name to the second node name) and return a
// Graph (Map) of each node name associated with the Set of all node names to
// which there is an edge from the key node name.
Graph read_graph(std::ifstream &file) {
Graph graph;
std::string line;
while (getline(file,line)) {
std::vector<std::string> nodes = ics::split(line,";");
if (!graph.has_key(nodes.at(0))) {
NodeSet s;
graph.put(nodes.at(0), s);
}
graph[nodes.at(0)].insert(nodes.at(1));
}
return graph;
}
//Print a label and all the entries in the Graph in alphabetical order
// (by source node).
//Use a "->" to separate the source node name from the Set of destination
// node names to which it has an edge.
void print_graph(const Graph& graph) {
std::string alphabet = "abcdefghijklmnopqrstuvwxyz";
for(unsigned long i=0;i<alphabet.size();++i) {
std::string t = alphabet.substr(i,1);
if(graph.has_key(t)) {
std::cout << t << "->" << graph[t]<<std::endl;
}
}
}
//Return the Set of node names reaching in the Graph starting at the
// specified (start) node.
//Use a local Set and a Queue to respectively store the reachable nodes and
// the nodes that are being explored.
//NodeSet reachable(const Graph& graph, std::string start) {
//
//}
//
//
//Prompt the user for a file, create a graph from its edges, print the graph,
// and then repeatedly (until the user enters "quit") prompt the user for a
// starting node name and then either print an error (if that the node name
// is not a source node in the graph) or print the Set of node names
// reachable from it by using the edges in the Graph.
int main() {
std::ifstream file;
try {
ics::safe_open(file,"Enter","../graph.txt");
if(file.is_open())
print_graph(read_graph(file));
else {
std::cout<<"fail"<<std::endl;
}
} catch (ics::IcsError& e) {
std::cout << e.what() << std::endl;
}
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment