Generating an array of random numbers without duplicates [duplicate]

送分小仙女□ 提交于 2020-11-29 10:15:38

问题


I have been banging my head for two days now trying to make sure the random generator method won't generate a duplicate. This I had to do with loops only without importing any libraries. I have come to this solution, will this code generate a duplicate on the long run? If yes please help.

int[] vargu1 = new int[5];

for (int i = 0; i < vargu1.length; i++) {
    int numriSekret = (int) (Math.random() * 10) + 1;
    vargu1[i] = numriSekret;
}

System.out.println(vargu1[i]);
System.out.println();

for (int i = 0; i < vargu1.length; i++) {
    for (int j = 0; j < i; j++) {
        if (vargu1[i] == vargu1[j]) {
            vargu1[i]++;
        }
        System.out.println(vargu1[i]);
    }
}

回答1:


Since you said without any libraries you could reimplement the Collections.shuffle(...) method for arrays.

int [] randoms = new int[5];

// creating an array containing the numbers 1-10
int [] shuffleArray = new int[10];
for (int i = 1; i <= 10; i++) {
    shuffleArray[i-1] = i;
}

// shuffling that array
Random random = new Random();
for (int i = 0; i < 10; i++) {
    int j = random.nextInt(10);
    int tmp = shuffleArray[i];
    shuffleArray[i] = shuffleArray[j];
    shuffleArray[j] = tmp;
}

// assigning the first 5 values to the random array
for (int i = 0; i < randoms.length; i++) {
    randoms[i] = shuffleArray[i];
}

Although i have to remark that Random needs an import too (needs a library too)




回答2:


As far as I understand what you are doing, a better way would/could be:

List<Integer> myList = new ArrayList<Integer>();
for ( int i = 0; i < expectedNumberOfUniques; i++){
  Integer a = generateRandom();
  while ( myList.contains(a)){
    a = generateRandom();
  }
  myList.add(a);
}

A few remarks, though: the more elements in myList, the less efficiënt it might be less efficiënt.

But: as soon as you limit it to 'no duplicates allowed', we are no longer talking about 'random' numbers.



来源:https://stackoverflow.com/questions/35056719/generating-an-array-of-random-numbers-without-duplicates

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!