Web Toolbar by Wibiya

## Saturday, November 12, 2011

### Write a program to shuffle a deck of cards.

Solution #1: The approach is to pick a card in sequence and replace it with another card picked at random from the remaining cards. Here is the code,

```#include
#include
#include

#define DECK_SIZE 52

//generate random number between a and b(both inclusive)
int gen_rand(int a, int b)
{
int num;

srand(time(NULL));

num = a + rand()%(b-a+1);

return num;
}

void shuffle(int *deck, int size)
{
int i=0;
int rand_pick=0;
int temp=0;

for(i=0; i < size; i++)
{
//pick a random card between current card and last card(both inclusive)
rand_pick = gen_rand(i, size);

//swap it with the current card
int temp = deck[rand_pick];
deck[rand_pick] = deck[i];
deck[i] = temp;
}
}

int main()
{
int deck[DECK_SIZE];

//initalize cards in serial order
int i=0;
for(i=0; i < DECK_SIZE; i++)
deck[i] = i;

shuffle(deck, DECK_SIZE);

//print cards
for(i=0; i < DECK_SIZE; i++)
printf("%d\n", deck[i]);

return 0;
}
```

Anonymous said...

interesting question :)

Anonymous said...

can u explain the logic of calculating random number in gen_rand(a,b)

num = a + rand()%(b-a+1);

Suchit Maindola said...

@Anonymous: rand()%n returns a number between '0' and 'n-1', both inclusive. So, here rand()%(b-a+1) returns a number between '0' and 'b-a', both inclusive. So, the final random number is between 'a+0' and 'a+b-a' i.e. 'a' and 'b', both inclusive.