Skip to content

Instantly share code, notes, and snippets.

@linzhp
Last active November 23, 2017 05:31
Show Gist options
  • Save linzhp/5efdf01533cf5d2d8271 to your computer and use it in GitHub Desktop.
Save linzhp/5efdf01533cf5d2d8271 to your computer and use it in GitHub Desktop.
Triangle counting in Python and Java
import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.Set;
import org.jgrapht.graph.DefaultEdge;
import org.jgrapht.graph.SimpleGraph;
public class App {
public static void main(String[] args) throws IOException {
SimpleGraph<Integer, DefaultEdge> graph = readGraph(args[0]);
System.out.println("Number of vetices: " + graph.vertexSet().size());
System.out.println("Number of edges: " + graph.edgeSet().size());
long start = System.currentTimeMillis();
System.out.println("Number of triangles: " + countTriangles(graph)/3);
System.out.println("Time elapsed: " + (System.currentTimeMillis() - start)/1000);
}
private static SimpleGraph<Integer, DefaultEdge> readGraph(String fileName) throws FileNotFoundException,
IOException {
FileReader file = new FileReader(fileName);
BufferedReader reader = new BufferedReader(file);
SimpleGraph<Integer, DefaultEdge> graph = new SimpleGraph<>(DefaultEdge.class);
String line = reader.readLine();
while (line != null) {
if (!line.startsWith("#")) {
String[] tokens = line.split("\\s+");
Integer node1 = Integer.valueOf(tokens[0]);
Integer node2 = Integer.valueOf(tokens[1]);
graph.addVertex(node1);
graph.addVertex(node2);
if (node1 != node2) {
graph.addEdge(node1, node2);
}
}
line = reader.readLine();
}
reader.close();
return graph;
}
private static int countTriangles(SimpleGraph<Integer, DefaultEdge> graph) {
int count = 0;
for (Integer v : graph.vertexSet()) {
Set<DefaultEdge> edges = graph.edgesOf(v);
int[] neighbors = new int[edges.size()];
int i = 0;
for (DefaultEdge e : edges) {
neighbors[i] = graph.getEdgeTarget(e);
if (neighbors[i] == v) {
neighbors[i] = graph.getEdgeSource(e);
}
i++;
}
for (i=0; i < neighbors.length; i++) {
for (int j = i + 1; j < neighbors.length; j++) {
if (graph.containsEdge(neighbors[i], neighbors[j]) ||
graph.containsEdge(neighbors[j], neighbors[i])) {
count++;
}
}
}
}
return count;
}
}
__author__ = 'Zhongpeng Lin'
"""
Graph algorithms implemented with networkx
"""
from networkx import Graph
import sys
import re
import itertools
import time
def read_graph(file):
g = Graph()
with open(file, 'r') as graph_file:
for line in graph_file:
if not line.startswith('#'):
nodes = re.split('\s+', line.strip(), 1)
if nodes[0] != nodes[1]:
g.add_edge(int(nodes[0]), int(nodes[1]))
return g
def wedge_iterator(graph):
for node in graph.nodes_iter():
neighbors = graph.neighbors(node)
for pair in itertools.combinations(neighbors, 2):
yield (node, pair)
def count_triangle(graph):
n = 0
for wedge in wedge_iterator(graph):
if graph.has_edge(wedge[1][0], wedge[1][1]) or graph.has_edge(wedge[1][1], wedge[1][0]):
n += 1
return n
if __name__ == '__main__':
g = read_graph(sys.argv[1])
print('Number of vertices:', g.number_of_nodes())
print('Number of edges:', g.number_of_edges())
n = 0
start_time = time.time()
n = count_triangle(g)
print('Number of triangles:', n/3)
print('Time used:', time.time() - start_time)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment