I am just starting to learn C++ and took the advice of this site on which book to start with, namely C++ without fear. So far I am doing well and understanding what the writer is teaching but then I ran into the card dealer. Nothing to hard to understand until he adds in the array to ensure that no card was picked twice. I know that it works but I am unclear on HOW and WHY it works. As far as I can understand, the code simply passes a location in the array and thats all. I cannot figure out where the program is told what to do at the location, that is, check for 1's and skip them. Can someone please help me understand how this works. I do not want to continue on with the book without understanding this. Thank you.
Code:
#include "stdafx.h"
#include <iostream>
#include <stdlib.h>
#include <time.h>
#include <math.h>
using namespace std;
int rand_0toN1(int n);
void draw_a_card();
int select_next_available(int n);
char *suits[4] = {"Hearts", "Spades", "Clubs", "Diamonds"};
char *ranks[13] = {"Ace", "Two", "Three", "Four", "Five", "Six", "Seven", "Eight",
"Nine", "Ten", "Jack", "Queen", "King"};
int card_drawn[52];
int cards_remaining = 52;
int main() {
int n, i;
srand(time(NULL));
while(1) {
cout << "Enter number of cards to draw (0 to Exit)";
cin >> n;
if (n == 0)
break;
for (i =1; i <= n; i++)
draw_a_card();
}
return 0;
}
void draw_a_card() {
int r, s, n, card;
n = rand_0toN1(cards_remaining--);
card = select_next_available(n);
r = card % 13;
s = card / 13;
cout << ranks[r] << " of " << suits[s] << endl;
}
int select_next_available(int n) {
int i = 0;
while (card_drawn[i])
i++;
while (n-- > 0){
i++;
while (card_drawn[i])
i++;
}
card_drawn[i] = true;
return i;
}
int rand_0toN1(int n) {
return rand() % n;
}