0

I'm creating a function to generate an arry of random and not repeating numbers.What am i doing wrong?

With this code the function fills the array repeating some numbers.

for(int i=0;i<n;i++)
        {
          numero = random.nextInt(delta) + da;
          for(int j=0;j<n;j++)
          {
            if(numero==estratti[j])
            {
              numero = random.nextInt(delta) + da;
              j=0;
            }        
          }
          estratti[i] = numero;
        }
Makoto
  • 104,088
  • 27
  • 192
  • 230
user7913
  • 9
  • 1

2 Answers2

2

The problem seems to occur if you randomly roll a duplicate number, then roll a new number, and randomly roll estratti[0]. You set j=0 when you find a duplicate, but the next time you check whether numero==estratti[j] is in the next iteration of the loop. By then, j has been incremented j++ to 1, hence you miss this case.

To fix it, you could set j = -1 if you find a duplicate number.

tobias_k
  • 81,265
  • 12
  • 120
  • 179
0

You should leverage an hashset structure and do something like this untested java code:

HashSet set = new LinkedHashSet();
while (set.size() < n) {
    set.add(random.nextInt(delta));
}
return set.toArray();

The HashSet.add method will not add a value if it is already present.

Adapt that code to your situation.

formixian
  • 1,549
  • 16
  • 25
  • While this generates unique random numbers, by doing `set.toArray` those numbers will be in sorted order (ordered by their hashcode, i.e. themselves). Better store them in a list or array and just use the set as a faster and more convenient way to check whether a number has already been rolled before. – tobias_k Jan 16 '19 at 20:53
  • You are right @tobias_k, a LinkedHashSet is in order here (keep the insertion order): https://docs.oracle.com/javase/9/docs/api/java/util/LinkedHashSet.html – formixian Feb 26 '19 at 00:35
  • But... no, the toArray will not return the generated numbers ordered by hashCode. They will be ordered according to the place they occupy in the backing array of linked list. Which is different than the insertion order but still just scrambled some more. You are mingling HashSet with SortedSet. – formixian Feb 26 '19 at 00:41