1

I am trying to give the items in the voice channel randomly to the items in the message content. but it chooses the same person again. how can I prevent this? also user like this for dont knowing discord.js ppl example = user = ["2222222", "21111112"]

let users = message.member.voiceChannel.members
.filter(y => y.user.id !== message.author.id)
.map(a => a.user.id);
for (var i = 0; i < num; i++) {
var user = users[Math.floor(Math.random() * num)];
console.log(user);
let adi = message.guild.members.get(user);
liste += "" + adi.displayName + " adlı kullanıcının rolü " + rol + "\n";
oyuncular += " <@" + adi.user.id + "> ";

}
O. Jones
  • 103,626
  • 17
  • 118
  • 172

2 Answers2

2

There are two kinds of random-selection methods, "roll" and "deal". Roll can get the same value more than once, as in rolling dice. Deal gets a different value, as in dealing cards.

You're using roll. You need deal. You need to remove each value from further consideration as you choose it.

Let's say you've populated your users array, and now you want to deal num values from it. To do this you removed each item from your array as you choose it. It's a job for splice().

for (let i = 0; i < num; i++) {
  if (users.length <= 0) break
  const randex = Math.floor(Math.random() * users.length)
  const user = users.splice(randex, 1)[0]
  /* do what you want with this user */
}

Splice is a good choice for this; the V8 Javascript engine developers worked hard to make it as efficient as possible.

You can test this by pasting the following code into your console REPL in your browser devtools.

(function deal (k, n) {
  function range1(i){return i?range1(i-1).concat(i):[]}
  const users = range1(n)
  for (let i = 0; i < k; i++) {
    if (users.length <= 0) break
    const randex = Math.floor(Math.random() * users.length)
    const user = users.splice(randex, 1)[0]
    console.log (user)
  }
})(7, 52)

This is a simplification of the Fisher-Yates (aka Knuth) shuffle algorithm mentioned here. That algorithm shuffles everything in the input array. But that's not necessary if you only need to sample a few items from a longer array.

O. Jones
  • 103,626
  • 17
  • 118
  • 172
0

What is 'num' in your example?

Surely the following would work:

var user = users[Math.floor(Math.random() * users.length)];