Compare elements in an array for duplicates

后端 未结 8 738
轻奢々
轻奢々 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:04

    this generates it in O(number of digits), no inner loops, no shuffling <- this could be expensive if the number of choices gets really big

    int[] digits = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 };
    Random random = new Random();
    
    int[] generateId() {
        int[] choices = digits.clone();
        int[] id = new int[5];
    
        for (int i = 0; i < 5; i++) {
            // one less choice to choose from each time
            int index = random.nextInt(choices.length - i);
            id[i] = choices[index];
            // "remove" used item by replacing it with item at end of range
            // because that index at the end won't be considered in next round
            choices[index] = choices[choices.length - i - 1];
        }
    
        return id;
    }
    

提交回复
热议问题