Create function that returns random numbers in C

1

I need to create a function that returns random numbers without repeating between 2 ranges.

I wanted to create a kind of a card game, where the cards are shuffled, and when they come back they never go out again.

In my code you are repeating the values.

Code withdrawn for privacy reasons

    
asked by anonymous 25.11.2014 / 20:04

1 answer

2

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 .

    
25.11.2014 / 20:10