lundi 10 décembre 2018

How can I choose a random element from an ArrayList if it changes size?

In my code "count0", "count1" and "count2" receive random values and "totalCount" is a sum of them. Here I have simplified it.

With this code I can choose a random element of the ArrayList but if for example "count0" is equal to 0 it will remove the index 0 from the ArrayList not only the first time but every iteration, causing error if this happens. The idea is how to randomly choose ingredients from a pantry and when one is exhausted you can still choose from the rest.

Thanks for the help =)

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Random;

public class RndNumArray {

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {

    int totalCount=4, count0=1, count1=1, count2=2;
    Random rnd = new Random();
    ArrayList<Integer> numbers = new ArrayList<>(Arrays.asList(0, 1, 2));

    while(totalCount>0){

        int rand = rnd.nextInt(numbers.size());
        int num = numbers.get(rand);
        if (num == 0) {
            count0--;
            if (ccount0 == 0) {
                numbers.remove(0);
            }
        }
        if (num == 1) {
            count1--;
            if (count1 == 0) {
                numbers.remove(1);
            }
        }
        if (num == 2) {
            count2--;
            if (count2 == 0) {
                numbers.remove(2);
            }
        }
        totalCount--;
        System.out.println(num);
    }
    }    
}




Aucun commentaire:

Enregistrer un commentaire