Compare elements in an array for duplicates

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

    If I understand you correctly, you want a random 5 digit number, with no digit repeated?

    If so, one way is to shuffle a list of the digits 0-9, then pick the first 5 elements.

    EDIT

    Integer[] digits = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9};
    Random random = new Random();
    
    public Integer[] generateId() {
        List id = Arrays.asList(digits);
        Collections.shuffle(id, random);
        return id.subList(0, 5).toArray(new Integer[0]);
    }
    

提交回复
热议问题