Created
April 10, 2012 06:50
-
-
Save thejefflarson/2348876 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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