AlgoPlus v0.1.0
Loading...
Searching...
No Matches
linked_list_visualization.h
1#ifndef LINKED_LIST_VISUALIZATION_H
2#define LINKED_LIST_VISUALIZATION_H
3
4#ifdef __cplusplus
5#include <chrono>
6#include <fstream>
7#include <iostream>
8#include <string>
9#endif
10
11using namespace std;
12
13// COLORS FOR TEXT
14
15namespace linked_list_visualization {
16
17#define OPEN_COMMAND "open"
18
19inline void visualize(std::string& _generate, std::string newFileName = "unnamed.dot") {
20 auto start_time = std::chrono::high_resolution_clock::now();
21 try {
22 if (newFileName.size() < 5 || newFileName.substr(newFileName.length() - 4) != ".dot")
23 newFileName += ".dot";
24 // newFileName = "examples/" + newFileName;
25 // Open the file for writing
26 std::ofstream outFile(newFileName);
27
28 // Check if the file is successfully opened
29 if (outFile.is_open()) {
30 // Write the DOT format header
31 outFile << "digraph list {" << std::endl;
32
33 // Generate DOT code recursively
34 outFile << _generate;
35 // Write the DOT format footer
36 outFile << "}" << std::endl;
37
38 // Close the file
39 outFile.close();
40
41 std::cout << "Visualization file '" << newFileName << "' created successfully."
42 << std::endl;
43 auto end_time = std::chrono::high_resolution_clock::now();
44 auto duration =
45 std::chrono::duration_cast<std::chrono::microseconds>(end_time - start_time);
46 double runtime_sec = static_cast<double>(duration.count()) / 1e6;
47
48 std::cout << "Visualization runtime: " << runtime_sec << " sec" << std::endl;
49 std::string openCommand = OPEN_COMMAND + std::string(" ") + newFileName;
50 system(openCommand.c_str());
51 } else {
52 std::cerr << "Error: Unable to open file '" << newFileName << "' for writing."
53 << std::endl;
54 }
55 } catch (const std::exception& e) {
56 std::cerr << "Error: " << e.what() << std::endl;
57 }
58};
59
60}; // namespace linked_list_visualization
61
62#endif // LINKED_LIST_VISUALIZATION_H