Choosing players based on ArrayList size

Discussion in 'Plugin Development' started by ShadowLAX, Sep 3, 2013.

Thread Status:
Not open for further replies.
  1. Offline

    ShadowLAX

    Hello bukkit, I am trying to figure out how to select random players based on an ArrayList's size. So say for every 10 elements in the arraylist, 1 player is chosen. Also, what if the number was like 7 or 13, how would I round it to the closest multiple of 10?

    Thanks!
     
  2. Offline

    Tarestudio

    ShadowLAX
    If you want the closest: (array.size() + 5) / 10
    With 15 you will get 2.
    For the random player, get the list of onlinplayers, create a random number and get the player at the random index.
     
  3. Offline

    ShadowLAX

    Tarestudio thanks, that helps a bit. What I need though with the players being picked is that with the number from the (array.size() + 5) / 10, which is 2, it would choose that number of random players. so say the number chose was 7, it would choose 7 random people.
     
  4. Offline

    Retherz_

    here is an example i use

    int random = new Random().nextInt(Main.classes.size());
    Player player = Main.classes.get(random);
    p.teleport(player.getLocation());
     
  5. Offline

    Tarestudio

    ShadowLAX
    Like this?
    Code:java
    1. Player[] players = Bukkit.getOnlinePlayers();
    2. Set<Player> result = new HashSet<Player>();
    3. while ( result.size() < ((array.size() + 5) / 10) ) {
    4. int random = new Random().nextInt(players.length);
    5. result.add(players[random]);
    6. }
     
  6. Offline

    CoderCloud

    I would use the Random bevore choosing the players.

    Code:java
    1. Player[] players = Bukkit.getOnlinePlayers();
    2. Player[] result = new Player[(int)((players.length+5)/10)];
    3. Set<Integer> picked = new HashSet<>();
    4. Random r = new Random();
    5.  
    6. for(int i = 0; i<result.length; i++){
    7. int pick = r.nextInt(players.length);
    8. for(int p : picked)
    9. if(p == pick)
    10. continue;
    11. result[i] = players[pick];
    12. picked.add(pick);
    13. }[/i]
     
  7. Offline

    Tarestudio

    CoderCloud
    This will fail on choosing multiple times the same the player, your for-loop increments everytime, no matter a player was added or not.
    Code:java
    1. Player[] players = Bukkit.getOnlinePlayers();
    2. Player[] result = new Player[(int)((players.length+5)/10)];
    3. Set<Integer> picked = new HashSet<>();
    4. Random r = new Random();
    5.  
    6. for(int index = 0; index < result.length && index < player.length; index++){
    7. int pick = r.nextInt(players.length);
    8. while ( picked.contains(pick) ) {
    9. pick = r.nextInt(players.length);
    10. }
    11. result[index] = players[pick];
    12. picked.add(pick);
    13. }
     
Thread Status:
Not open for further replies.

Share This Page