Quicky App
Quicky App

Reputation: 123

How to stop duplicates values in an array in 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;
    }
  }
}

Upvotes: 2

Views: 137

Answers (3)

Ananda Raju
Ananda Raju

Reputation: 9

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

Upvotes: 1

VladP
VladP

Reputation: 537

Deleted since downvoted. That is a reason why it is removed.

Upvotes: 0

Bathsheba
Bathsheba

Reputation: 234715

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

Upvotes: 8

Related Questions