Random Java Algorithm

Discussion in 'Plugin Development' started by davidclue, Sep 14, 2021 at 3:46 PM.

  1. Offline

    davidclue

    Alright so this question is about java in general basically, I have 10 possibilities (1-10) and I want to cycle through all of them at random. Right now I have a switch statement that uses a random number and if the case is invalid it just adds +1 to the case number and checks the next case and so on till it finds a valid case or it has iterated through all 10 cases. What I want is a way to iterate through all 10 cases at random and without iterating through the same case again so how would I go about doing this?
     
  2. Offline

    Dai_Kunai

    An array with 1-10 (or 0-9) in it, where you pick a random element out of the array and then remove that element out of the array. Instead of those numbers you could use whatever your "10 possibilities" are if they can go inside an array.

    You should use an arrayList so that you can remove them; there may be a better way than this though. A while loop checking that the arrayList isn't empty would work, though a for loop can as well. Then you use random to pick an index from 0 to the array list length - 1 and get the possibility that's at that index and use it and remove it.
     
  3. Offline

    davidclue

    @Dai_Kunai Well I thought of that before but the calculations I am running can get really heavy and using an array list would be very performance heavy so I am looking for another way to use an algorithm of some sort.
     
  4. Offline

    timtower Administrator Administrator Moderator

  5. Offline

    davidclue

    @timtower Simply I have 10 different cases that I want to all be cycled by at random, a solution would be what @Dai_Kunai mentioned but the problem with it is that with the calculations I am doing it would be very inefficient to use ArrayLists for this.
     
  6. Offline

    timtower Administrator Administrator Moderator

    @davidclue Make an interface, let 10 classes implement that interface with their own algorithm, add the classes to a list, select in random and execute the method.
     
  7. Offline

    davidclue

    @timtower Nvm after trying some things I got an efficient solution, here's what I was talking about I probably explained it bad.
    Code:
    int[] options = {1,2,3,4,5,6,7,8,9,10};
    while (options.length <= 0) {
        int r = ThreadLocalRandom.current().nextInt(1, options.length+1);
        switch (options[r]) {
            //all 10 cases
        }
        options = ArrayUtils.remove(options, r);
    }
     
  8. Offline

    KarimAKL

    An array's length will never be below 0. Also, you initialize the array with a size of 10, so the while loop would just be skipped.
     
  9. Offline

    davidclue

    @KarimAKL Typo, I just typed it up real quick I didn't copy it over. Also just force of habit to put <= 0 instead of == 0
     

Share This Page