Enable Javascript in your browser and then refresh this page, for a much enhanced experience.
First solution in Clear category for [old] New Cities by mortonfox
"use strict";
function subnetworks(net, crushes) {
let nodes = new Set(net.reduce((accum, conn) => accum.concat(conn), []));
for (let node of crushes) {
nodes.delete(node);
}
let subcount = 0;
while (nodes.size) {
++ subcount;
// Is there a better way to pop() from a Set?
let [node] = nodes;
let stack = [node];
nodes.delete(node);
while (stack.length) {
node = stack.pop();
for (let conn of net) {
if (node === conn[0] && nodes.has(conn[1])) {
stack.push(conn[1]);
nodes.delete(conn[1]);
}
else if (node === conn[1] && nodes.has(conn[0])) {
stack.push(conn[0]);
nodes.delete(conn[0]);
}
}
}
}
return subcount;
}
var assert = require('assert');
if (!global.is_checking) {
assert.equal(subnetworks([
['A', 'B'],
['B', 'C'],
['C', 'D']
], ['B']), 2, "First")
assert.equal(subnetworks([
['A', 'B'],
['A', 'C'],
['A', 'D'],
['D', 'F']
], ['A']), 3, "Second")
assert.equal(subnetworks([
['A', 'B'],
['B', 'C'],
['C', 'D']
], ['C', 'D']), 1, "Third")
console.log("Done! Check button is waiting for you!");
}
July 28, 2017