Hi, I am working out the book C++ Without Fear, and I am in ch 5, trying to understand a concept in example 5.5: optimizing the program. This is the code I had:
while (1) {
cout << "Enter number of cards to draw, or press 0 to exit: ";
cin >> n;
if (n == 0) {
break;
}
for (i = 1; i <= n; i++) {
draw_a_card();
}
}
return 0;
}
//draw_a_card function, obtaining a random 0-4 of suits string array, and a random 0-12 of ranks string array.
void draw_a_card() {
int r, s;
int n, card;
n = rand_0to(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_0to(int n) {
return rand() % n;
}
-------------------------------------------------------------------------
Now, I am pretty sure I understand all this, it's when I am asked to optimize it that I am lost, here are the changes:
if (cards_remaining == 0) {
cout << "Reshuffling." << endl;
cards_remaining = 52;
for (int i = 0; i < 52; i++) {
card_drawn[i] = false;
}
}
This is suppose to be inserted into the draw_a_card function, so I just did that below the other code. This was fine for me. The following code is what lost me...
int select_next_available(int n) {
int i = -1;
n++; //THIS IS WHERE I GET LOST
while (n-- > 0) {
i++;
while (card_drawn[i]) {
i++;
}
}
card_drawn[i] = true;
return i;
}
He says: "That because we use the while loop, in the select_next_available function twice, it can be folded together into one, by realizing that the function advances through the array not n times, but n + 1 times. I don't understand, and why is the solution to this, to replace the while statement with n++...I just see that as negating the following while statement (n--). Any help in understanding is appreciated.
The first version of select_next_available executes a bit of code while (card_drawn[i]) { i++; } first once, and then n more times. This can be converted to a single loop which executes the bit n+1 times. Note that i needs to be initialized to -1 in the second version.