Skip to content

Instantly share code, notes, and snippets.

@bvipul
Created August 9, 2018 07:42
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save bvipul/0536338ae49c62cc1fd1ce1af8555e99 to your computer and use it in GitHub Desktop.
Save bvipul/0536338ae49c62cc1fd1ce1af8555e99 to your computer and use it in GitHub Desktop.
Creating unions for union find using Node.js readline
const readline = require('readline');
const unions = [];
const rl = readline.createInterface({
input: process.stdin,
output: process.stdout
});
let number = undefined, i = 0;
rl.on('line', (line) => {
if(typeof(number) != 'undefined') {
line = line.split(" ");
let a = parseInt(line[0].trim()),
b = parseInt(line[1].trim());
union(a, b);
if(++i >= number) {
console.log("unions", unions);
rl.close();
}
}
else {
number = parseInt(line);
}
});
function union(a, b) {
if(unions.length == 0) {
unions.push([a, b]);
} else {
const val1 = unions.findIndex((val) => {
return val.indexOf(a) !== -1;
});
const val2 = unions.findIndex((val) => {
return val.indexOf(b) !== -1;
});
if(val1 == -1 && val2 == -1) {
unions.push([a, b]);
} else if(val1 !== -1 && unions[val1].indexOf(b) == -1) {
unions[val1].push(b);
} else if(val2 !== -1 && unions[val2].indexOf(a) == -1) {
unions[val2].push(a);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment