> Fill the array in sequentially and then shuffle it.
According to me, this is the best strategy. You are guaranteed that every number is unique and you add randomization through shuffling.
Implementation should be fairly straight-forward:
- a for-loop to fill the array
- a random number of exchanges which involve two randomly selected indexes
That's all.
If you need a matrix structure (i.e. a bi-dimensional array), you can do as we said with a mono-dimensional array, then you can fill a matrix with the values you obtain from the array.
Ok, I haven't tried your code but is seems ok. I just want you to notice one thing: you say
do {
pick a random number
} while (this number is not good)
Well... since rand is random (actually pseudo-random but anyway...) you are not guaranteed that this code will be able to terminate. Imagine this situation: you have your array which is
n -1 -1 -1 ....................................... -1
where n is the last element you have to put in the matrix and is located at position 0. Then you are not guaranteed that sooner or later 0 will be picked by the rand function. Actually this happens (probably after a while) but it is not 100% reliable.
Instead the solution we were discussing before is this one:
#include <iostream>
#include <cstdlib>
#include <ctime>
void swap(int array[], int pos1, int pos2) {
int tmp = array[pos1];
array[pos1] = array[pos2];
array[pos2] = tmp;
}
int main() {
srand(time(NULL));
int numbers[100];
int matrix[10][10];
// fill in the numbers
for (int i = 0; i < 100; ++i) {
numbers[i] = i;
}
// a random number of swaps
int repeat = rand() % 100 + 100;
// perform the swaps...
for (int i = 0; i < repeat; ++i) {
// ... with random positions
swap(numbers, rand() % 100, rand() % 100);
}
// fill in the matrix
for (int i = 0; i < 10; ++i) {
for (int j = 0; j < 10; ++j) {
matrix[i][j] = numbers[i * 10 + j];
}
}
std::cout << "This is the matrix:" << std::endl << std::endl;
// print the matrix
for (int i = 0; i < 10; ++i) {
for (int j = 0; j < 10; ++j) {
std::cout << matrix[i][j] << " ";
}
std::cout << std::endl;
}
return 0;
}
And here there is no guessing: it starts, works and completes. Always! :)