Randomly get Half of the strings in a list.

Discussion in 'Plugin Development' started by PatoTheBest, Jan 27, 2014.

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

    PatoTheBest

    Can someone help me with getting half the players (Strings) from a list??

    Code:java
    1. public void pickRnadom(){
    2. int playerThatWillBePicked = ((inGamePlayers.size() >= 6) ? inGamePlayers.size()/2 : 1);
    3.  
    4. Random random = new Random();
    5.  
    6. for (String player1 : AlivePlayers){
    7.  
    8. Player player = Bukkit.getPlayer(player1);
    9.  
    10. //do stuff
    11. }
    12. }
     
  2. Offline

    felixfritz

    You could shuffle AlivePlayers and pick those players from index 0 up.
     
  3. Offline

    PatoTheBest

    I need help with that. I am experienced with Java but not with Random().
     
  4. Offline

    felixfritz

    Collections.shuffle(AlivePlayers); will shuffle the collection - then just take out index 0 to, I guess, playerThatWillBePicked - 1.

    You could also be fancier than that and create your own little shuffle-syntax.
    Code:java
    1. int playerThatWillBePicked = /* ... */;
    2. Random random = new Random();
    3.  
    4. int index;
    5. Player p;
    6. for(int x = 0; x < playerThatWillBePicked; x++) {
    7.  
    8. index = random.nextInt(AlivePlayers.size() - x);
    9. p = Bukkit.getPlayer(AlivePlayers.get(index));
    10.  
    11. /*version 1 to switch with the last index*/
    12. String tmp = AlivePlayers.get(index);
    13. AlivePlayers.remove(index);
    14. AlivePlayers.add(tmp);
    15.  
    16. /*version 2 to switch with the last index*/
    17. int lastIndex = AlivePlayers.size() - x - 1;
    18. String tmp = AlivePlayers.get(index);
    19. AlivePlayers.set(index, AlivePlayers.get(lastIndex));
    20. AlivePlayers.set(lastIndex, tmp);
    21. }
     
  5. Offline

    PatoTheBest

    Can I do this?
    Code:java
    1. public void pickRandomTNT(){
    2. int playerThatWillBePicked = ((inGamePlayers.size() >= 6) ? inGamePlayers.size()/2 : 1);
    3.  
    4. Random random = new Random();
    5.  
    6. String[] players = (String[]) AlivePlayers.toArray();
    7.  
    8. while (playerThatWillBePicked != 0){
    9. int randomInt = random.nextInt(AlivePlayers.size());
    10. TNTPlayers.add(players[randomInt]);
    11. AlivePlayers.remove(randomInt);
    12. playerThatWillBePicked--;
    13. }
    14. }/syntax]
     
Thread Status:
Not open for further replies.

Share This Page