Adding numbers to a 2D array with no duplicates

For a module in college I have to make a game. I don't have much experience with coding but basically the game is a 3x3 board, with numbers 0-8 and they are initially in a random order. The aim of the game is to move the '0' and get the board back in to order. I can't have duplicate numbers in the boards 2D array.
This is the code for my board constructor:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
cout << "Enter your PlayerName for the leaderboard" << endl;
	cin >> playerName;
	limit = 10000;

	int alreadySeen[9];
	for (int i = 0; i < 3; i++) {
		for (int j = 0; j < 3; j++) { 
			int r = rand() % 8 + 0; 
			bool inAlreadySeen = false; 
			while (inAlreadySeen == false) {
				int k = 0; 
				for (; k < 9; k++) {
					if (alreadySeen[k] == r) { 
						break; 
					}
				}
				if (k == 9) {
					inAlreadySeen = true;
				}
				else {
					r = rand() % 8 + 0; 
				}
			}
			board[i][j] = r; 
	}
	for (int i = 0; i < 3; i++) {
		for (int j = 0; j < 3; j++) {
			if (board[i][j] == 0) {
				row = i; 
				column = j;
			}
		}
	}
}


The output is giving me duplicate numbers. I think this is because I'm never actually adding anything to the alreadySeen array? But I have messed about with it, tried to add the random number to it and it doesnt seem to work. Can anyone tell me where I should add to the already seen array?
Last edited on
You don't want random numbers. You want numbers 0-8. One of each. What you do want to be random is their order. A deck of cards has one of each. The deck is shuffled. An example:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
#include <iostream>     // std::cout
#include <numeric>      // std::iota
#include <algorithm>    // std::shuffle
#include <random>       // std::default_random_engine
#include <chrono>       // std::chrono::system_clock

int main () {
  constexpr size_t N { 9 };
  int numbers[N];
  std::iota( numbers, numbers+N, 0 );
  std::cout << "numbers:";
  for ( int& i : numbers ) std::cout << ' ' << i;
  std::cout << "\n\n";

  // obtain a time-based seed:
  unsigned seed = std::chrono::system_clock::now().time_since_epoch().count();

  shuffle( numbers, numbers+N, std::default_random_engine(seed) );

  std::cout << "shuffled:";
  for ( int& i : numbers ) std::cout << ' ' << i;
  std::cout << "\n\n";

  for ( int row = 0; row < 3; ++row ) {
    for ( int col = 0; col < 3; ++col )
      std::cout << ' ' << numbers[ row * 3 + col ];
    std::cout << '\n';
  }
  return 0;
}
Topic archived. No new replies allowed.