Creating random numbers with no duplicates

后端 未结 18 1776
忘了有多久
忘了有多久 2020-11-21 12:00

In this case, the MAX is only 5, so I could check the duplicates one by one, but how could I do this in a simpler way? For example, what if the MAX has a value of 20? Thanks

18条回答
  •  旧巷少年郎
    2020-11-21 12:15

    It really all depends on exactly WHAT you need the random generation for, but here's my take.

    First, create a standalone method for generating the random number. Be sure to allow for limits.

    public static int newRandom(int limit){
        return generatedRandom.nextInt(limit);  }
    

    Next, you will want to create a very simple decision structure that compares values. This can be done in one of two ways. If you have a very limited amount of numbers to verify, a simple IF statement will suffice:

    public static int testDuplicates(int int1, int int2, int int3, int int4, int int5){
        boolean loopFlag = true;
        while(loopFlag == true){
            if(int1 == int2 || int1 == int3 || int1 == int4 || int1 == int5 || int1 == 0){
                int1 = newRandom(75);
                loopFlag = true;    }
            else{
                loopFlag = false;   }}
        return int1;    }
    

    The above compares int1 to int2 through int5, as well as making sure that there are no zeroes in the randoms.

    With these two methods in place, we can do the following:

        num1 = newRandom(limit1);
        num2 = newRandom(limit1);
        num3 = newRandom(limit1);
        num4 = newRandom(limit1);
        num5 = newRandom(limit1);
    

    Followed By:

            num1 = testDuplicates(num1, num2, num3, num4, num5);
            num2 = testDuplicates(num2, num1, num3, num4, num5);
            num3 = testDuplicates(num3, num1, num2, num4, num5);
            num4 = testDuplicates(num4, num1, num2, num3, num5);
            num5 = testDuplicates(num5, num1, num2, num3, num5);
    

    If you have a longer list to verify, then a more complex method will yield better results both in clarity of code and in processing resources.

    Hope this helps. This site has helped me so much, I felt obliged to at least TRY to help as well.

提交回复
热议问题