0

I'm trying to figure out whats the most simple way to add to fill this 2D Array with only non duplicate numbers.

I've tried to use a method with boolean to check the value before adding it, if it already exists but I couldn't make it work.

int[][] x = new int[R][C];

for (int i = 0; i < x.length; i++) {
    for (int j = 0; j < x[i].length; j++) {
        double z = (Math.random() * ((30 * (j + 1)) - ((30 * j) + 1)) + 1 + ((30 * j) + 1));
        card[i][j] = (int) z;
    }
}

2 Answers2

0

You definitely want to use Random.nextInt() to get a uniform distribution of your int. Most likely you want a Set to track which numbers were already generated.

int[][] cards = new int[ROW][COL];
Random r = new Random();
Set<Integer> generated = new HashSet<>();
for (int i = 0; i < ROW; i++) {
  for (int j = 0; j < COL; j++) {
    int n;
    do {
      n = r.nextInt();
    } while (generated.contains(n));
    generated.add(n);
    cards[i][j] = n;
  }
}
Karol Dowbecki
  • 43,645
  • 9
  • 78
  • 111
  • Then it's not random anymore. The question was specifically about using Random numbers. – Ramu Nov 09 '19 at 14:49
0

The best way i will say is to use Set data structure

int row = 2;
int col = 2;
Set<Set<Integer>> rowSet = new HashSet<>();

 for (int i = 0; rowSet.size() < row; i++) {
        Set<Integer> colSet = new HashSet<>(); 

    for (int j = 0; colSet.size() < col; j++) {
    double x = (Math.random() * ((15 * (j + 1)) - ((15 * j) + 1)) + 1 + ((15 * j) + 1));
    colSet.add((int) x);
  }
   rowSet.add(colSet);
}

And finally convert them to array

int[][] arr = set.stream()
                     .map(i->i.stream()
                             .mapToInt(Integer::intValue)
                             .toArray())
                     .toArray(int[][]::new);
Ryuzaki L
  • 37,302
  • 12
  • 68
  • 98