Solved Random ItemStack with percentage

Discussion in 'Plugin Development' started by ScopeTowel, Feb 12, 2020.

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

    ScopeTowel

    Hey guys, I need your help ! I need to have a random ItemStack with percentage. Like if you had 3 ItemStack :

    ItemStack blueWool = new ItemStack(Material.WOOL, 1, (byte)11);
    ItemStack redWool = new ItemStack(Material.WOOL, 1, (byte)14);
    ItemStack greenWool = new ItemStack(Material.WOOL, 1, (byte)13);

    Now I want to chose one of this 3 ItemStack randomly but with percentage like

    blueWool = 30%
    redWool = 50%
    greenWool = 20%

    How I can do that ?
     
  2. Offline

    CraftCreeper6

    @ScopeTowel
    There's a few ways.

    The not so great way:

    For each percent that an item possesses, add it to a List that many times. So if it's 50%, add it to a List 50 times and then just use a random to choose from the list.

    The better way:
    Use cumulative probability. (the second answer on the link I sent)

    It uses Math to pick a random element.

    It should be noted that if using cumulative probability, "This algorithm requires the probabilities to be normalized (divided by the sum of all probabilities). By doing that you ensure that Σp_i=1 and then a random number between 0 and 1 will do the trick" (aioobe, StackOverflow)
     
  3. Offline

    caderapee

    @ScopeTowel just pick a random number between 0 and 1, 1 is 100%, and do a if else. Check 0.5 0.8 and 1
     
  4. Offline

    ScopeTowel

    else you can do something like this no :

    int randomchance = r.nextInt(100) + 1;

    if(randomchance < 50){
    //give red wool
    }else if (randomchance < 80) {
    //give blue wool
    }else if (randomchance < 90) {
    //give green wool
    }else (randomchance <= 100) {
    //give purple wool
    }

    Can I do that ?
     
  5. Offline

    KarimAKL

Thread Status:
Not open for further replies.

Share This Page