Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Generate random numbers except certain values

I want to generate random numbers, but don't want them to be from exclude array. Here is my code.

public int generateRandom(int start, int end, ArrayList<Integer> exclude) {
    Random rand = new Random();
    int range = end - start +1 - exclude.size();
    int random = rand.nextInt(range) + 1;

    for(int i = 0; i < exclude.size(); i++) {
        if(exclude.get(i) > random) {
            return random;
        }
      random++;
    }

    return random;
}

I use this function in a while loop, and during each iteration I add a new value to exclude. Sometimes it returns numbers that belong to exclude. What's the problem?

like image 690
user2081119 Avatar asked Feb 18 '13 12:02

user2081119


People also ask

How do you exclude a number in math randomly?

math. random when specified with two values returns a number in the range [m, n]. -1 < 0 < 1 therefore 0 is a valid number in this range. You can't exclude a number, so your best bet would be to do randomise again until the result is not 0.

How do you generate random numbers in a certain range?

Method 1: Using Math. random() function is used to return a floating-point pseudo-random number between range [0,1) , 0 (inclusive) and 1 (exclusive). This random number can then be scaled according to the desired range.


1 Answers

this worked for me:

    public int randomInt(int start, int end, int... exception) {
        int result = -1;
        Random rand = new Random();
        int range = end - start + 1;
        boolean equals = true;

        while(equals) {
            result = rand.nextInt(range);
            boolean differentOfAll = true;
            for(int i : exception) {
                if(result==i) {
                    differentOfAll = false;
                    break;
                }
            }
            if(differentOfAll) {
                equals = false;
            }
        }

        return result;
    }
like image 68
edilon Junior Avatar answered Oct 09 '22 02:10

edilon Junior