Skip to content

Instantly share code, notes, and snippets.

@pimiento pimiento/max_connected.js Secret
Last active Feb 13, 2016

Embed
What would you like to do?
max connected
function processData(input) {
"use strict";
var data = input.split("\n"),
n = +data[0],
m = +data[1],
line = 2,
adj = [];
function connect(a, b) {
var t = adj[b];
for (let i = 0; i < adj.length; i++) {
if (adj[i] === t)
adj[i] = +adj[a];
}
};
function getMax() {
var d = {}, max = 0;
for (let e of adj)
if (typeof d[e] === "undefined")
d[e] = 1;
else
d[e] += 1;
for (let k in d)
if (d[k] > max && k > -1)
max = d[k];
return max;
};
function ijTo1D(i, j) {
return i*n + j;
};
function connectPrev(i, j) {
if (j > 0 && adj[ijTo1D(i, j-1)] >= 0) // left
connect(ijTo1D(i, j), ijTo1D(i, j-1));
if (i > 0 && adj[ijTo1D(i-1, j)] >= 0) // up
connect(ijTo1D(i, j), ijTo1D(i-1, j));
if (i > 0 && j > 0 && adj[ijTo1D(i-1, j-1)] >= 0) // left up
connect(ijTo1D(i, j), ijTo1D(i-1, j-1));
if (i > 0 && j+1 < m && adj[ijTo1D(i-1, j+1)] >= 0)// right up
connect(ijTo1D(i, j), ijTo1D(i-1, j+1));
};
function printAdj(delimeter) {
console.log(delimeter);
for (let i = 0; i < n; i++) {
let t = [];
for (let j = 0; j < n; j++) {
t.push(adj[ijTo1D(i, j)]);
}
console.log(t);
}
console.log(delimeter);
};
while (line < n+2) {
let elements = data[line].split(" "),
i = line-2;
for (let j = 0; j < elements.length; j++) {
let idx = ijTo1D(i, j);
if (elements[j] === "0") {
adj[idx] = -1;
} else {
adj[idx] = idx;
connectPrev(i, j);
}
}
line++;
}
console.log(getMax());
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.