Skip to content

Instantly share code, notes, and snippets.

@SirVer
Created August 15, 2012 18:42
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 SirVer/3362265 to your computer and use it in GitHub Desktop.
Save SirVer/3362265 to your computer and use it in GitHub Desktop.
Actor centrality in Cplusplus
#include <set>
#include <string>
#include <map>
#include <fstream>
#include <iostream>
#include <vector>
#include <stdint.h>
using namespace std;
struct Node {
string name;
set<Node*> neighbours;
};
struct Graph {
map<string, Node> nodes;
vector<string> actors;
};
struct SortEntry {
double val;
string name;
bool operator<(const SortEntry & other) const {
return val < other.val;
}
};
Graph read_graph() {
char line[1024];
ifstream fin;
Graph G;
set<string> seen_actors;
fin.open("imdb-1.tsv");
while (!fin.eof()) {
string actor, movie;
fin.getline(line, sizeof(line));
size_t eol = strlen(line) + 1;
int state = 0;
size_t cs = 0;
for (size_t i = 0; i < eol; ++i) {
if (line[i] == '\t' or line[i] == 0) {
line[i] = 0;
if (state == 0) {
actor = (line+cs);
++state;
cs = i+1;
} else if (state == 1) {
movie = (line+cs);
++state;
cs = i+1;
} else if (state == 2) {
movie += "_";
movie += (line+cs);
Node & an = G.nodes[actor]; an.name = actor;
Node & mn = G.nodes[movie]; mn.name = movie;
an.neighbours.insert(&mn);
mn.neighbours.insert(&an);
if (!seen_actors.count(actor)) {
G.actors.push_back(actor);
seen_actors.insert(actor);
}
}
}
}
}
return G;
}
double actor_centrality(Graph & G, string name) {
map<Node*, uint64_t> dists;
set<Node*> next; next.insert(&G.nodes[name]);
set<Node*> nnext;
set<Node*> *pnext = &next, *pnnext = &nnext;
uint64_t cdist = 0;
while (!pnext->empty()) {
pnnext->clear();
for (Node * n : *pnext) {
if (!dists.count(n)) {
dists[n] = cdist;
for (Node * nn : n->neighbours) {
if (!dists.count(nn))
pnnext->insert(nn);
}
}
}
++cdist;
set<Node*>* temp = pnnext;
pnnext = pnext; pnext = temp;
}
double sum = 0;
for (auto p : dists)
sum += p.second;
return sum / dists.size();
}
int main(int argc, char const *argv[])
{
Graph g = read_graph();
sort(g.actors.begin(), g.actors.end());
vector<SortEntry> tree;
for(int i =0; i < 100; ++i) {
SortEntry e = {actor_centrality(g, g.actors[i]), g.actors[i]};
cout << g.actors[i] << endl;
tree.push_back(e );
}
sort(tree.begin(), tree.end());
for(int i =1; i <=20; ++i)
cout << i << ": " << tree[i-1].name << ", " << tree[i-1].val << endl;
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment