/* CPP w/o Fear, by Overland. Exercise 05.03.01.txt, p. 126. Write a program that randomly selects from a bag of eight objects. Each object can be red, blue, orange, or green, and it can be a ball or a cube. Assume the bag contains one object for each combination (one red ball, one red cube, one orange ball, one orange cube, and so on). Write code similar to dealer1.cpp, using two string arrays-- one to identify colors and the other to identify shapes. */ #include #include #include using namespace std; int rand_0toN1(int n); void draw_an_item(); char *colors[4] = {"red", "blue", "orange", "green"}; char *shapes[2] = {"ball", "cube" }; int main() { int n, i; srand(time(NULL)); // Set seed for random numbers. while (1) { cout << "Enter no. of items to draw (0 to exit): "; cin >> n; if (n == 0) break; for (i = 1; i <= n; i++) draw_an_item(); } return 0; } // Draw-an-item function // Performs one item-pick by getting a random 0-4 and a random // 0-1. These are then used to index the string arrays, colors // and shapes // void draw_an_item() { int c; // Random index (0 thru 4) into colors array int s; // Random index (0 thru 1) into shapes array c = rand_0toN1(4); s = rand_0toN1(2); cout << colors[c] << " " << shapes[s] << endl; } // Random 0-to-N1 Function. // Generate a random integer from 0 to N-1. // int rand_0toN1(int n) { return rand() % n; }