Solved Set variable to weighted random value

Discussion in 'Plugin Development' started by SmearySubset, Jun 12, 2021.

  1. Offline

    SmearySubset

    Hello, I want to make it so, when a zombie spawns, it has a 10% chance of having normal walking speed, 40% chance of having a 1.1 walking speed multiplier, and a 50% chance of it having a 1.25 walking speed multiplier. I know how to handle the attributes part of it, but I'm unsure how to create the weights (10%, 40%, 60%).

    Thanks!
    Smeary Subset

    Also, the zombies will be spawning via the plugin, not naturally.
     
    Last edited: Jun 12, 2021
  2. Offline

    c7dev

    You could generate a random number, and then return a decimal value for the speed multiplier for the zombie's speed attributes.
    Code:
    public static double rngMultiplier() {
        Random r = new Random();
        int k = r.nextInt(10);   //random number 0-9
         
        if (k <= 3) return 1.1;   //values 0, 1, 2, 3 (4/10 = 40%)
        else if (k <= 8) return 1.25;   //values 4, 5, 6, 7, 8 (5/10 = 50%)
        else return 1;   //remaining 10%
    }
     
  3. Offline

    Shqep

    See Random, SecureRandom or ThreadLocalRandom.
    Basically, you want to generate a number from 1-10 for example, and if it's 1 (10%) -> normal speed, if it's 2-3-4 (30%) -> 1.1 speed, and if it's the other 5-6-7-8-9-10 (60%) -> 1.25 speed.
     
  4. Offline

    SmearySubset

    @c7dev thanks so much. Originally I was going to use an array of 100 values to select a random value from there, but your way is much more memory efficient.

    @c7dev This is actually my first forum post... how do you mark it as solved?

    EDIT by Moderator: merged posts, please use the edit button instead of double posting.
     
    Last edited by a moderator: Jun 13, 2021
  5. Offline

    KarimAKL

    At the top right of the page, you can click "Thread Tools" and set the title prefix to "Solved."
     

Share This Page