C++ Primer Plus Chapter 7 Exercise 4

c plus plusThe trick to this program is understanding what is it asking and getting it to work as it wants. In my solution I created a second function that holds all the numbers plus the probability function within it. I think this is one of the quickest solution to this exercise. The output is truncated to that of a long int, as I think the book format is quite ugly. Another way I had though of doing this originally was to calculate the odds of 1 in 47, store it. Calculate the 1 in 27 odds, store it, then find the product of those all in their own functions. That idea seemed clumsy when coding it and all roads were pointing to the solution provided for me.

Many state lotteries use a variation of the simple lottery portrayed by Listing 7.4. In
these variations you choose several numbers from one set and call them the field numbers.
For example, you might select 5 numbers from the field of 1–47). You also pick a
single number (called a mega number or a power ball, etc.) from a second range, such as
1–27. To win the grand prize, you have to guess all the picks correctly. The chance of
winning is the product of the probability of picking all the field numbers times the probability
of picking the mega number. For instance, the probability of winning the example
described here is the product of the probability of picking 5 out of 47 correctly times the
probability of picking 1 out of 27 correctly. Modify Listing 7.4 to calculate the probability
of winning this kind of lottery.

#include <iostream>

using namespace std;

// Note: some implementations require double instead of long double
long double probability(unsigned numbers, unsigned picks);
long int TotalOdds(int, int, int, int, long double(*p)(unsigned, unsigned));

int main()
{
cout << "Welcome to the Powerball!\n";
cout << "Odds of winning are one in " << TotalOdds(47, 5, 27, 1, probability);
cout << "\nThanks for playing!" << endl;

return 0;
}
// the following function calculates the probability of picking picks
// numbers correctly from numbers choices
long double probability(unsigned numbers, unsigned picks)
{
long double result = 1.0; // here come some local variables
long double n;
unsigned p;
for (n = numbers, p = picks; p > 0; n--, p--)
result = result * n / p;
return result;
}

long int TotalOdds(int FirstSet, int x, int PowerBall, int y, long double(*p)(unsigned, unsigned))
{
long double odds;
odds = p(FirstSet, x)*p(PowerBall, y);
return odds;
}