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*>, this is vector of nodes and each node has vector<Node*>, which is vector of neighbours
- Assistant
Finding the global clustering coefficient of a graph involves counting the number of closed triplets (triangles) in the graph and dividing by the total number of connected triples. Below is a C++ code that computes the global clustering coefficient of a graph given the desired input data structure:
#include <iostream> #include <vector> #include <unordered_set> using namespace std; class Node { public: int val; vector<Node*> neighbors; Node(int _val) { val = _val; } }; double global_clustering_coefficient(vector<Node*>& nodes) { int triangles = 0; int connected_triples = 0; for (Node* node : nodes) { unordered_set<int> node_neighbor_ids; for (Node* neighbor : node->neighbors) { node_neighbor_ids.insert(neighbor->val); } int degree = node->neighbors.size(); connected_triples += degree * (degree - 1) / 2; for (Node* neighbor : node->neighbors) { for (Node* neighbor_of_neighbor : neighbor->neighbors) { if (node_neighbor_ids.count(neighbor_of_neighbor->val)) { triangles++; } } } } triangles /= 6; // Each triangle is counted 6 times. return static_cast<double>(triangles) / connected_triples; } int main() { vector<Node*> nodes(5); for (int i = 0; i < nodes.size(); ++i) { nodes[i] = new Node(i); } // Creating a simple undirected graph nodes[0]->neighbors = {nodes[1], nodes[2]}; nodes[1]->neighbors = {nodes[0], nodes[2], nodes[3]}; nodes[2]->neighbors = {nodes[0], nodes[1], nodes[4]}; nodes[3]->neighbors = {nodes[1]}; nodes[4]->neighbors = {nodes[2]}; cout << "Global clustering coefficient: " << global_clustering_coefficient(nodes) << endl; for (Node* node : nodes) { delete node; } return 0; }Note that this code assumes that the input graph is undirected, and it does not contain any self-loops or duplicate edges. Adjusting the code to specific requirements might be necessary, depending on the actual graph data.
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.