I shuffle and pair the user ids as you can see below.
/**
* @see https://stackoverflow.com/a/12646864
* @param {string[]} array
*/
const shuffleArray = (array) => {
for (let i = array.length - 1; i > 0; i--) {
const j = Math.floor(Math.random() * (i + 1));
[array[i], array[j]] = [array[j], array[i]];
}
return array;
};
/**
* @see https://stackoverflow.com/a/44996257
* @param {string[]} array
*/
const pairArray = (array) => {
return array.reduce(function (result, value, index, array) {
if (index % 2 === 0) result.push(array.slice(index, index + 2));
return result;
}, []);
};
const getRandomUsers = async () => {
let userIDSet = [];
const users = await svc.findAll({ enrolled: true });
if (!Object.keys(users).length) {
console.log("DAMN! There are no users enrolled yet. What a bummer!");
}
for (const user of users) {
userIDSet.push(user.discordId);
}
const shuffledUserIDs = shuffleArray(userIDSet);
const pairedUserIDs = pairArray(shuffledUserIDs);
return pairedUserIDs;
};
After running getRandomUsers(), a method checks for non-pair (odd) elements. If any, notify the user and delete from matchmaking array.
The problem is: These matches will repeat in a certain time. But I don't want the same users to match again.
For example:
const userArray = [1, 2, 3, 4, 5, 6];
const shuffleForFirst = shuffleArray(userArray);
const firstMatchmaking = pairArray(shuffleForFirst);
console.log("First Matchmaking:", firstMatchmaking);
const shuffleForSecond = shuffleArray(userArray);
const secondMatchmaking = pairArray(shuffleForSecond);
console.log("Second Matchmaking:", secondMatchmaking);