-1

i want to generate random numbers without duplicate from 1 to n^2 (e.g. n=3, numbers in range of 1 to 9) in 2D array and i don't want to use list, but my code generated the numbers duplicate, how can i fix this ? here is my code :

for(int i=0; i<n; i++){
   for(int j=0; j<n; j++){
      array[i][j] = rand.nextInt((n * n) - 1) + 1;
   }
}
parsaaa
  • 19
  • 3
  • @samabcde No i want to don't use list – parsaaa Mar 08 '21 at 07:34
  • 2
    generating a list with values, shuffling it and getting the randomized values one by one seems to be quite reasonable. An alternative is to create a set to track the generated values and generate random values until a unique number is detected. – Nowhere Man Mar 08 '21 at 07:48
  • 1
    `No i want to don't use list` @parsaaa then state it in the question, not after people provide an answer – Dropout Mar 08 '21 at 07:57

1 Answers1

0

One way is to generate a sequential collection, shuffle it and put the shuffled elements in your array.

List<Integer> numbers = new ArrayList<>();
for (int i = 1; i <= n * n; i++) {
    numbers.add(i);
}
Collections.shuffle(numbers);
int index = 0;
for (int i = 0; i < n; i++) {
    for (int j = 0; j < n; j++) {
        array[i][j] = numbers.get(index);
        index++;
    }
}
geco17
  • 5,152
  • 3
  • 21
  • 38
  • It generates numbers range of 0 to n² - 1. –  Mar 08 '21 at 07:42
  • I updated the answer. It generated numbers from 0 - n^2 - 1 becaues of how I initialized it. Look at the first for loop. – geco17 Mar 08 '21 at 07:48