Generate Random Number Array and Replace Duplicate

2019-08-14 18:50发布

I am generating an array of 6 ints within a range of 1- 54 (similar to lotto numbers). However, when trying to detect duplicates, my code is not executing. I tried to debug by simply printing "WE HAVE FOUND A DUPLICATE" if my conditional logic would catch a duplicate. Of course, it doesn't print the desired output:

18-33-39-41-41-45

I want to detect the duplicate so that I can generate another random number that is not equal to the discovered duplicate. I don't want to just increment/decrement the duplicate's value just to get another number, I want to actually generate another value between 1&54 that is not equal to the duplicate.

Here is my code:

public class Main {

    public static void main(String[] args) {

        Random rand = new Random();
        int[] luckyArray = new int[6];

        //build array
        for (int i = 0; i < luckyArray.length; i++) {

            int luckyNumber = rand.nextInt(54) + 1;
            luckyArray[i] = luckyNumber;
        }
        //detect duplicates in the array
        for (int i = 0; i < luckyArray.length; i++) {
            if (i > 0 && luckyArray[i] == luckyArray[i - 1]) {
                System.out.print("WE HAVE FOUND A DUPLICATE!");
                /* while (luckyArray[i - 1] == luckyArray[i]) {
                    luckyArray[i] = rand.nextInt(54) + 1;
                }*/
            }
        }
        //sort the array before printing
        Arrays.sort(luckyArray);
        for (int t = 0; t < luckyArray.length; t++) {

            if (t != 5) {
                System.out.print(luckyArray[t] + "-");
            } else System.out.print(luckyArray[t]);
        }
    }
}

I expected to compare the current index [i] to that of its previous [i-1] and if/when they are equal, produce a new value for the current index.

Thanks in advance!

5条回答
在下西门庆
2楼-- · 2019-08-14 19:16

Here is a very simple solution using Java 8 streams:

int[] luckyArray = new Random().ints(1, 55).distinct().limit(6).sorted().toArray();

This doesn't bother detecting duplicates manually - instead it uses distinct to remove them prior to choosing the first 6 and then sorting them.

查看更多
Summer. ? 凉城
3楼-- · 2019-08-14 19:18

With Java 8:

List<Integer> luckys = 
    IntStream.rangeClosed(1, 54)
             .boxed()
             .collect(collectingAndThen(toList(), l -> {
                 Collections.shuffle(l);
                 return l;
             }))
             .stream()
             .limit(6)
             .collect(toList())
查看更多
时光不老,我们不散
4楼-- · 2019-08-14 19:20

I would (personally) rely on the properties of a Set here to ensure that you're not retaining duplicates at all - you don't even have to check for dupes:

    Random rand = new Random();
    int numNumsToGenerate = 6;
    Set<Integer> luckySet = new HashSet<Integer>();

    //build set
    while (luckySet.size() < numNumsToGenerate) {
        luckySet.add(rand.nextInt(54) + 1);
    }

Once you've established your set, you can then sort them by creating a new List with the contents of your Set:

//sort the array before printing
List<Integer> luckyList = new ArrayList<Integer>(luckySet);
Collections.sort(luckyList);
查看更多
啃猪蹄的小仙女
5楼-- · 2019-08-14 19:22

Move the 'sort' up, before you check for duplicates. This way you can be sure duplicates are always located next to each other and you only need to check neighbors.

Here the code that detects duplicates:

package luckynumber;

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

public class Main {

    public static void main(String[] args) {

        Random rand = new Random();
        int[] luckyArray = new int[6];

        // build array
        for (int i = 0; i < luckyArray.length; i++) {

            int luckyNumber = rand.nextInt(54) + 1;
            luckyArray[i] = luckyNumber;
        }
        // sort the array before detecting duplicates
        Arrays.sort(luckyArray);
        // detect duplicates in the array
        for (int i = 0; i < luckyArray.length; i++) {
            if (i > 0 && luckyArray[i] == luckyArray[i - 1]) {
                System.out.print("WE HAVE FOUND A DUPLICATE!");
                /* while (luckyArray[i - 1] == luckyArray[i]) { luckyArray[i] =
                 * rand.nextInt(54) + 1; } */
            }
        }
        for (int t = 0; t < luckyArray.length; t++) {

            if (t != 5) {
                System.out.print(luckyArray[t] + "-");
            } else
                System.out.print(luckyArray[t]);
        }
    }
}

When you now find a duplicate and change the array item make sure to re-sort and re-check the complete array. This remaining step is left as an exercise for the reader. ;-)

BTW: using Set will make the code much simpler.

查看更多
小情绪 Triste *
6楼-- · 2019-08-14 19:25

If sets are not an option you'll need to make a check that iterates through your array each time. Your current check only compares sequential number 1&2, 2&3 etc.

Alternately assign your lucky number to be checked to an int to be checked against your array before insertion.

查看更多
登录 后发表回答