Random function
I imagine you just want to use a function like this. Creating one is not a very simple task. better use what is already ready.
#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;
}
Behold working in the ideone. And in the repl it.. Also put on the Github for future reference.
Documentation of the function rand()
and srand()
can be found here.
Algorithm without repetition
I believe the complete solution you are accurate is based on the algorithm Fisher-Yates. Something like that (if I agree with that response in the OS):
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;
}
}
So now is to adapt to your need.
Deck
I found an example more or less ready for what you want on that 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]);
}
Behold working in the ideone. And in the repl it.. Also put on the Github for future reference.
Hi Marconi. Why did you delete the question, even with such a complete answer? By the way, you have already deleted several questions! Remember that the content posted here on the site is not for specific users, but for the entire internet. An answer that solves your problem can also solve other people’s. We moderators talked and decided to undo the deletion of this question, okay? From now on, please think twice before deleting a post. If you would like to discuss the matter, we are available. Thank you.
– bfavaretto
@bfavaretto Questions that exclude or have not been answered, or have been poorly planned. I apologize. Before deleting them I will rethink the questions.
– Marconi
Okay Marconi, thank you for understanding.
– bfavaretto