Created
August 13, 2020 01:47
-
-
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.
This file contains hidden or 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
| 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