質問

i just started compsci here in high school and I am trying to make a card game.

My teacher wants us to create a function that shuffles and deals out the cards randomly (user can input how many decks they want to use). I've spent hours thinking on how to do this and have come up with a few ideas. I want to represent each card with an int value and then assign a card value based on that number. To do this I basically want to just divide the number by mod 4, to get a 1-4 value (the suit value).

The problem, however, is that I dont know how to assign a card value (Ace, Two, Three.... etc) Im thinking the best way to do this would be do group everything by multiples of 4. I've been thinking for a long time and still have not figured out a way to accomplish this. Any ideas would help tremendously. Thank you!

役に立ちましたか?

解決

Take the number mod 4 for the suit (giving a number from 0 to 3). Take the number divided by 4 for the value (giving a number from 0 to 12, which you can add 1 to in order to have a value from 1 to 13). Remember that integer division will return the "floor" of the mathematically exact answer.

For multiple decks, you'd first divide by 4, then take that mod 13 (then add 1 if you want).

A common shuffling algorithm (in C) :

void shuffle_deck(int *deck) {
    for (int i = DECKSIZE - 1; i > 1 ; --i) {
        int r = rand() % (i + 1);   
        int t = deck[r];  
        deck[r] = deck[i];
        deck[i] = t;
    }
}
ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top