Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to stop duplicates values in an array in C

Tags:

c

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;
    }
  }
}
like image 317
Quicky App Avatar asked Jan 24 '26 09:01

Quicky App


2 Answers

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

like image 175
Bathsheba Avatar answered Jan 26 '26 00:01

Bathsheba


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

like image 37
Ananda Raju Avatar answered Jan 26 '26 00:01

Ananda Raju