Write me a code in C++ that finds global clustering coefficient of graph. I have…
- User
Write me a code in C++ that finds global clustering coefficient of graph. I have vector<Node*> and in each element of that I have vector<Node*> as neighbours and int id
- Assistant
Here is a C++ code that computes the global clustering coefficient of a graph given a vector of Node pointers, where each Node has an id and a vector of neighbor Node pointers. You can modify the class definition to fit your implementation.
#include <iostream> #include <vector> #include <unordered_set> class Node { public: int id; std::vector<Node*> neighbours; Node(int _id) : id(_id) {} void addNeighbour(Node* node) { neighbours.push_back(node); } }; double globalClusteringCoefficient(std::vector<Node*> graph) { int totalTriangles = 0; int totalTriplets = 0; for (Node* node : graph) { int degree = node->neighbours.size(); int localTriangles = 0; if (degree < 2) { continue; } for (Node* neighA : node->neighbours) { for (Node* neighB : node->neighbours) { if (neighA == neighB) { continue; } std::unordered_set<Node*> commonNeighbours(neighA->neighbours.begin(), neighA->neighbours.end()); commonNeighbours.erase(node); commonNeighbours.insert(neighB->neighbours.begin(), neighB->neighbours.end()); if (commonNeighbours.size() < neighA->neighbours.size() + neighB->neighbours.size()) { localTriangles++; } } } totalTriangles += localTriangles; totalTriplets += degree * (degree - 1); } return totalTriangles * 1.0 / totalTriplets; } int main() { Node* A = new Node(1); Node* B = new Node(2); Node* C = new Node(3); Node* D = new Node(4); A->addNeighbour(B); A->addNeighbour(C); A->addNeighbour(D); B->addNeighbour(A); B->addNeighbour(C); C->addNeighbour(A); C->addNeighbour(B); D->addNeighbour(A); std::vector<Node*> graph = {A, B, C, D}; double clusteringCoeff = globalClusteringCoefficient(graph); std::cout << "Global clustering coefficient: " << clusteringCoeff << std::endl; return 0; }
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.