Skip to content

Instantly share code, notes, and snippets.

@khoazero123
Created August 13, 2020 01:47
Show Gist options
  • Select an option

  • Save khoazero123/61cfb84f0cb8cc7b523ba4dedc776311 to your computer and use it in GitHub Desktop.

Select an option

Save khoazero123/61cfb84f0cb8cc7b523ba4dedc776311 to your computer and use it in GitHub Desktop.
You are developing a social network. 2 people are considered to be friends if they know each other or have a friend in common. If 2 people are friends they will be in the same group of friends.
function count_groups(friend_pairs) {
let [numFriendPair, numElementsOfElment, ...numOfArray] = friend_pairs.split("\n");
let formatedArr = [];
for (let i = 0; i < numOfArray.length; i++) {
const [idA, idB] = numOfArray[i].trim().split(' ');
formatedArr.push([idA, idB]);
}
let newArr = [[...formatedArr[0]]];
for (let i = 1; i < formatedArr.length; i++) {
const [idA, idB] = formatedArr[i];
let isMatch = false;
for (let x = 0; x < newArr.length; x++) {
if (newArr[x] && newArr[x].includes(idA)) {
newArr[x].push(idB);
isMatch = true;
} else if (newArr[x] && newArr[x].includes(idB)) {
newArr[x].push(idA);
isMatch = true;
}
}
if (!isMatch) {
newArr.push([idA, idB]);
}
}
return newArr.length;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment