Advertisement
Lucky_Dummy

Connected Graph generator

Nov 8th, 2023
718
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 2.14 KB | Source Code | 0 0
  1. #include <iostream>
  2. #include <cstddef>
  3. #include <queue>
  4. #include <vector>
  5. #include <random>
  6.  
  7. using AdjacencyMatrix = std::vector<std::vector<int>>;
  8.  
  9. AdjacencyMatrix generateGraph(size_t vertexes, float edgesRate)
  10. {
  11.     AdjacencyMatrix matrix = AdjacencyMatrix(vertexes, std::vector<int>(vertexes, 0));
  12.     size_t edges = (size_t)(vertexes * (vertexes - 1) / 2 * edgesRate);
  13.     if (edges + 1 < vertexes)
  14.     {
  15.         std::cout << "Current rate " << edgesRate << " is too small for connected graph with " << vertexes << " vertexes\n";
  16.         edges = vertexes - 1;
  17.     }
  18.  
  19.     std::mt19937 mt(time(nullptr));
  20.     {
  21.         std::vector<bool> used = std::vector<bool>(vertexes, false);
  22.         used[mt() % vertexes] = true;
  23.         for (size_t i = 1; i < vertexes; ++i)
  24.         {
  25.             int u;
  26.             do { u = mt() % vertexes; }
  27.             while (used[u]);
  28.             int v;
  29.             do { v = mt() % vertexes; }
  30.             while (!used[v]);
  31.             matrix[u][v] = matrix[v][u] = 1;
  32.             used[u] = true;
  33.         }
  34.     }
  35.    
  36.     for (size_t i = vertexes - 1; i < edges; ++i)
  37.     {
  38.         int u, v;
  39.         do {
  40.             u = mt() % vertexes;
  41.             v = mt() % vertexes;
  42.         } while (u == v || matrix[u][v] == 1);
  43.         matrix[u][v] = matrix[v][u] = 1;
  44.     }
  45.  
  46.     return matrix;
  47. }
  48.  
  49. std::vector<AdjacencyMatrix> genNGraphs(int countOfGraphs, int countOfVertexes, float edgesRate)
  50. {
  51.     std::vector<AdjacencyMatrix> graphs;
  52.     for (int k = 0; k < countOfGraphs; ++k)
  53.     {
  54.         bool newGraph = true;
  55.         AdjacencyMatrix graph;
  56.         do {
  57.             graph = generateGraph(countOfVertexes, edgesRate);
  58.             for (auto& g : graphs)
  59.             {
  60.                 newGraph = false;
  61.                 for (int i = 0; i < g.size(); ++i)
  62.                 {
  63.                     if (g[i] != graph[i])
  64.                     {
  65.                         newGraph = true;
  66.                         break;
  67.                     }
  68.                 }
  69.                 if (newGraph) break;
  70.             }
  71.         } while (!newGraph);
  72.         graphs.push_back(graph);
  73.     }
  74.     return graphs;
  75. }
Tags: graph
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement