Skip to content

Commit

Permalink
remove an edge when there's cycles
Browse files Browse the repository at this point in the history
  • Loading branch information
matthewmueller committed Feb 8, 2016
1 parent e2a2837 commit a18d7c4
Show file tree
Hide file tree
Showing 2 changed files with 9 additions and 10 deletions.
8 changes: 4 additions & 4 deletions index.js
Expand Up @@ -16,6 +16,10 @@ function toposort(graph) {
let s = sources(g);
let l = [];

for (let c of g.cycles()) {
g.removeExistingEdge(c.pop(), c.shift())
}

while (s.length) {
let n = s.shift(); // vs pop?
l.push(n);
Expand All @@ -28,10 +32,6 @@ function toposort(graph) {
}
}

if (g.edgeCount()) {
throw new Error('cycle detected in graph, topological sort is impossible');
}

return l;
}

Expand Down
11 changes: 5 additions & 6 deletions test/index.js
Expand Up @@ -13,17 +13,16 @@ describe('toposort(graph)', function () {
assert.isArray(toposort(graph));
});

it('should throw when the graph has a cycle', function () {
// a -> b -> c -> b* (cycle)
it('should handle graphs that have a cycle', function () {
// a -> b -> c -> d -> b* (cycle)
var graph = new Graph(
[ [ 'a', 'b' ] ],
[ [ 'b', 'c' ] ],
[ [ 'c', 'b' ] ]
[ [ 'c', 'd' ] ],
[ [ 'd', 'b' ] ]
);

assert.throws(function () {
toposort(graph);
});
assert.deepEqual(toposort(graph), ['a', 'b', 'c', 'd'])
});

it('should correctly sort a simple tree', function () {
Expand Down

0 comments on commit a18d7c4

Please sign in to comment.