I am creating a 5x5 board game in C. The problem I am having is that when I use the rand() it duplicates some of the numbers. How do I stop the duplicates and 0's?
Sorry if too basic a question. I'm new to C.
int createboard() {
int rows;
int columns;
int board[5][5];
int board2[5][5];
srand(time(NULL));
for (rows = 0; rows < 5; rows++) {
for (columns = 0; columns < 5; columns++) {
randomNumber = rand() % 25;
board[rows][columns] = randomNumber;
}
}
}
rand() would not be a particularly good generator if the probability of drawing the same number twice was zero.
A standard approach here would be to generate the board with consecutive numbers, then shuffle it by swapping elements at random a certain number of times.
A good shuffling algorithm is https://en.wikipedia.org/wiki/Fisher%E2%80%93Yates_shuffle
Use srand() function instead of rand function. rand() will give same numbers after each program. Refer this for help. This is for improvement of your program this is not answer Rand() vs srand() function
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With