Compare elements in an array for duplicates

后端 未结 8 814
轻奢々
轻奢々 2020-12-21 00:34

I am trying to generate a 5 digit int array in Java and am having trouble on where to start. None of the numbers in the array can be duplicates. I can generate

8条回答
  •  忘掉有多难
    2020-12-21 01:06

    try this:

    int[] digits = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 };
    Random random = new Random();
    
    int[] generateId() {
        int[] clone = digits.clone();
        int[] id = new int[5];
    
        for (int i = 0; i < 5; i++) {
            int candidate;
    
            do {
                candidate = random.nextInt(10);
            } while (clone[candidate] == -1);
    
            id[i] = clone[candidate];
            clone[candidate] = -1;
        }
    
        return id;
    }
    

提交回复
热议问题