Created
August 9, 2018 07:42
-
-
Save bvipul/0536338ae49c62cc1fd1ce1af8555e99 to your computer and use it in GitHub Desktop.
Creating unions for union find using Node.js readline
This file contains 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
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