I have a list of users and I have also list of pairs of matched users. i-e
const users = ["A", "B", "C", "D", "E", "F", "G"];
const alreadyMatchedUsers = [
{ user1: 'A', user2: 'B' },
{ user1: 'A', user2: 'C' },
]
I want to find list of unique unmatched users. By unique, I mean user pair AB and BA will be considered as 1 pair.
Here is the solution I have came up with:
const alreadyMatchedUsers = [
{ user1: 'A', user2: 'B' },
{ user1: 'A', user2: 'C' },
]
const unMatchedArrary = []
// const users = ['A', 'B', 'C', 'D']
const users = []
for (let i = 0; i < 300; i++) users.push(i)
const n = users.length
const uniquePossiblePairs = []
const uniquePossiblePairsCount = (n * (n - 1)) / 2
for (let i = 0; i < n - 1; i++) {
console.log('Main loop+++++++++++++++++', users[i])
for (let j = i; j < n - 1; j++) {
// uniquePossiblePairs.push({ user1: users[i], user2: users[j + 1] });
const alreadyMatched = alreadyMatchedUsers.some(
(mpair) => (users[i] === mpair.user1 || users[i] === mpair.user2)
&& (users[j + 1] === mpair.user1 || users[j + 1] === mpair.user2),
)
if (!alreadyMatched) {
unMatchedArrary.push({ user1: users[i], user2: users[j + 1] })
}
console.log('Already Matched, ', users[i], users[j + 1], alreadyMatched)
}
}
console.log('UNIQUE POSSIBLE PAIRS Count', uniquePossiblePairsCount)
console.log('UNIQUE POSSIBLE PAIRS', uniquePossiblePairs)
console.log('UNMATCHED ARRARY ', unMatchedArrary)
}
This solutions gives the expected results, But its very expensive operation. Try running this code with 300 users and if alreadyMatched users gets bigger, it will become way more expensive.
How can I get this to be faster?
Thanks