samedi 17 août 2019

Can't get stable result with copying random values from array to an object

So I've been in process of creating a bot for a tournament and I got stuck on the part where I want to split players in pair for play-off-style tournament. I just want to take 2 random players, write them into and array and write it as a value to a key as a round id for an object.
Here's the code:

var users = inc.funcs.getDatabase() //Getting a raw array of users (using my func that's basically a simplified fs.readFileSync func)
var tournamentPairs = new Object() //Object initialization

var id = 1
for (var i = 0; i < 16; i = i + 2) {
   var first = Math.floor(Math.random() * (users.length + 1)) //Randomizing 2 indexes
   var second = Math.floor(Math.random() * (users.length + 1))

   var player1 = client.users.get(users[first]) //Getting the players by id 
   var player2 = client.users.get(users[second])

   tournamentPairs[id++] = [player1.id, player2.id] //Writing to the object

   users.splice(first, 1)
   users.splice(second, 1)
}
console.log(tournamentPairs)

It works perfectly on the outside, but has a bad habit of duplicating users and I once could have a gamergod98 vs gamergod98 for example. I tried console.log this crap but it often get an error when trying to console.log player2 because it's undefined for some reason. If I try to print users[second] I get undefined thought it never happened for the fist player. So I try different ways to prevent situations like this: first == second. Long story short it didn't help much.
I have 9 days 'till tournament starts, any ideas on how to improve this code?




Aucun commentaire:

Enregistrer un commentaire