Skip to content

Instantly share code, notes, and snippets.

@thejefflarson
Created April 10, 2012 06:50
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save thejefflarson/2348876 to your computer and use it in GitHub Desktop.
Save thejefflarson/2348876 to your computer and use it in GitHub Desktop.
// Takes an adjacency list like:
// { 1: [2, 3], 2: [1, 3], 3: [2, 1] }
function pick(arr) {
var idx = (arr.length * Math.random()) | 0;
return arr[idx];
}
function remove(arr, el){
var idx;
while((idx = arr.indexOf(el)) > -1)
arr.splice(idx, 1);
}
function minCut(graph) {
var node, edge;
while(Object.keys(graph).length > 2) {
// pick a node
node = pick(Object.keys(graph));
// pick an edge
edge = pick(graph[node]);
// concat the array
graph[node] = graph[node].concat(graph[edge]);
// delete other vertex
delete graph[edge];
// update edges in other lists
Object.keys(graph).forEach(function(it){
var idx;
while((idx = graph[it].indexOf(edge)) > -1) graph[it][idx] = node;
});
// remove self loops
remove(graph[node], node);
}
return graph[Object.keys(graph)[0]].length;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment