can anyone help me with this code i just cant understand !
its about filling a deck of cards
thx

for (i = 0; i < 52; i++) 
{  
  deck[i] = (i % 13)<<2;
  deck[i] += i / 13;
 if(i/13 < 2)
  deck[i] += 64;

Recommended Answers

All 5 Replies

Yes. As i understand it's something about card game, these calculations are likely used for generating some random numbers. The % operator gives the remainder, so i % 13 always gives a number from 0 to 12, if i is positive, no matter what value i has. The << operator increases the number by shifting it left by one binary place, which means that << 1 is the same as multiplying by 2, << 2 the same as multiplying by 4, but a left shift is much faster than multiplying. What this gives is a random number which changes by a certain bigger unit, say by 4, which is sometimes necessary for a certain random behaviour. And then, i += i / 13 is just the same as i = i + i / 13...

The OP's code is also missing a closing curly bracket (}) at the end of the for loop.

This code is equivalent, but simpler:

for (i = 0; i < 52; i++) 
{  
  deck[i] = i % 13;  /* i modulo 13 */
  deck[i] = i * 2;
  deck[i] = deck[i] + i / 13;
 if(i/13 < 2)
  deck[i] = deck[i] + 64;
}

The modulo operator is explained in detail here: http://en.wikipedia.org/wiki/Modulo_operation

I see now that this code doesn't generate random numbers, but some kind of distribution, still the same applies.

wel this code fit inside a fuction which fill a deck of cards (52 cards)
knowing that ->

static char *s[] = {"Hearts","Diamonds","Clubs","Spades"};
static char *v[]  = {"Ace","Two","Three","Four","Five","Six",\
                        "Seven","Eight","Nine","Ten","Jack",\
                        "Queen","King"};
static char *c[]= {"Black","Red"};

actually i cant understand the logic behind this function
is it like creating a memory space for 52 cards so we can deal with it later or just creating cards...
because there is 2 other functions that show you the deck, shuffle the deck and print the deck again(shuffled).

for (i = 0; i < 52; i++) 
{  
  deck[i] = (i % 13)<<2;
  deck[i] += i / 13;
 if(i/13 < 2)
  deck[i] += 64;
 }

Actually, I don't understand it, either. The shifting and adding 64 makes no sense.

Since a deck has 52 cards, the loop is going through all the possible cards of the deck (0-51). Then (i / 13) gives you 0-4, representing the suit of the given card. (i % 13) gives the value or rank of the card (0-12). Therefore, if i is 5 you get the 6 of Hearts.

If you want to shuffle the deck, you can then yse the random generator to move cards to different random positions.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.