randomization???

Discussion in 'Plugin Development' started by mastermustard, Feb 16, 2013.

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

    mastermustard

    how would you go about randomizing a set of methods?

    for example these 3 messages get randomly picked:

    player.sendMessage("hi");
    player.sendMessage("sup");
    player.sendMessage("hey");

    its a bad way to example but thats the idea
     
  2. Offline

    Hoolean

    Code:java
    1. String[] greetings = {"hi", "sup", "hey"};
    2.  
    3. player.sendMessage(greetings[new Random().nextInt(greetings.length)]);
    4.  
    5. //or something similar ;D
     
  3. i would chose this code!
     
  4. Offline

    mastermustard

    thanks would this be able to go for any method?
     
  5. Offline

    Hoolean

    Hopefully ;D

    Depends what in particular you want but it should work with all Arrays :)

    If you want a version with lists:

    Code:java
    1. List<String> greetings = new ArrayList<String>();
    2.  
    3. greetings.add("hi");
    4. greetings.add("sup");
    5. greetings.add("hey");
    6.  
    7. player.sendMessage(greetings.get(new Random().nextInt(greetings.size())));
    8.  
     
  6. Offline

    finalblade1234

    Or you could do it the uneffecent way:
    Code:
     
    String hi = "hi";
    String sup =  "sup";
    String hey = "hey";
                int n = 1 + (int)(Math.random() * 3);
                if(n == 1){
                    event.getPlayer().sendMessage(hi);
                }else if(n == 2){
                                    event.getPlayer().sendMessage(sup);
                }else if(n == 3){
                    event.getPlayer().sendMessage(hey)
                }
            }
     
  7. Offline

    mastermustard

    any clue how i could go about "weighting" different ones so like "hi" has a better chance than "hey"
     
  8. Offline

    Tirelessly

    Add it in the array again.
     
    MrBluebear3 likes this.
  9. Offline

    microgeek

    Of you could use the Apache RandomUtils class, no need to make a new instance of Random.
    Example:
    return RandomUtils.nextInt(10) == 0;
    //1 in 10 chance
     
Thread Status:
Not open for further replies.

Share This Page