简体   繁体   中英

random not excluding my number

I currently am making an app. My app involves having 3 different buttons that have randomized values from 1-3, however each value needs to be used up. So the way I set up my code is I have a method that randomizes a number and excludes certain numbers. This works perfectly with constants, however with these the values sometimes overlap and equal each other. Why is this happening?

private void randomizeKeys(){
    key1 = (int)(Math.random()*3+1);
    key2 = getRandomWithExclusion(new Random(),1,3,key1);
    int[] arr1 = {key2,key1};
    key3 = getRandomWithExclusion(new Random(),1,3,arr1);


}

private int getRandomWithExclusion(Random rnd, int start, int end, int... exclude) {
    int random = start + rnd.nextInt(end - start + 1 - exclude.length);
    for (int ex : exclude) {
        if (random < ex) {
            break;
        }
        random++;
    }
    return random;
}

output example: key1 = 1, key2 = 2, key3 = 1 however key3 should equal 3

You should use a debugger to see what exactly is causing the bug to happen in your code. (hint: you're breaking out of the loop too early)

Another way to achieve the same goal of generating 3 random numbers is:

List<Integer> numbers = Arrays.asList(1, 2, 3);
Collections.shuffle(numbers);

Now you can use numbers.get(0) for the first key, numbers.get(1) for the second key, and so on.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM