Random function
I imagine you just want to use such a function. Create one is not a task very simple . better to use what already exists.
#include <time.h>
#include <stdlib.h>
#include <stdio.h>
int main(void) {
srand(time(NULL));
int r = rand() %13; //é número de cartas de cada naipe
printf("Número sorteado %d", r);
return 0;
}
See running on ideone . And in Coding Ground . Also I put it in GitHub for future reference .
The documentation for the function rand()
and srand()
can be found here .
Algorithm without repetition
I believe the complete solution you need is based on the Fisher-Yates algorithm. Something like this (agree to this answer in SO ):
int rand_int(int n) {
int limit = RAND_MAX - RAND_MAX % n;
int rnd;
do {
rnd = rand();
} while (rnd >= limit);
return rnd % n;
}
void shuffle(int *array, int n) {
int i, j, tmp;
for (i = n - 1; i > 0; i--) {
j = rand_int(i + 1);
tmp = array[j];
array[j] = array[i];
array[i] = tmp;
}
}
Now it's adapting to your need.
Deck
I found an example more or less ready for what you want on this page .
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#define CARDS 52
#define DRAW 5
void showcard(int card);
int main() {
int deck[CARDS];
int c;
/* initialize the deck */
for (int x = 0; x < CARDS; x++) deck[x] = 0;
srand((unsigned)time(NULL));
for (int x = 0; x < DRAW; x++) {
for(;;) { /* loop until a valid card is drawn */
c = rand() % CARDS; /* generate random drawn */
if(deck[c] == 0) { /* has card been drawn? */
deck[c] = 1; /* show that card is drawn */
showcard(c); /* display card */
break; /* end the loop */
}
} /* repeat loop until valid card found */
}
}
void showcard(int card) {
char *suit[4] = { "Spades", "Hearts", "Clubs", "Diamonds" };
switch (card % 13) {
case 0:
printf("%2s","A");
break;
case 10:
printf("%2s","J");
break;
case 11:
printf("%2s","Q");
break;
case 12:
printf("%2s","K");
break;
default:
printf("%2d",card%13+1);
}
printf(" of %s\n",suit[card/13]);
}
See running on ideone . And in Coding Ground . Also put it in GitHub for future reference .