Download: Reese.zip

Reference

Greg Reese, C++ Standard Library Practical Tips Charles River Media, 2006. ISBN 1-58450-400-5. p. 407-410.


numeric_function.cpp


// numeric_function.cpp

#include <algorithm>
#include <numeric>
#include <vector>

#include "tips.hpp"

int factorial( int n );
int teams( int candidate_size, int team_size );

using namespace std;

int main( )
{
   // make a vector with 0, 1, 2, 3, 4, 5
   vector<int> numbers( 6, 1 );
   numbers[0] = 0;
   partial_sum( numbers.begin(), numbers.end(), numbers.begin() );

   // compute the factorial of each number
   vector<int> result( 6 );
   transform( numbers.begin(), numbers.end(), result.begin(),
      factorial );
   tips::print( result, "Factorials of 0-5" );

   // candidates available and team sizes for baseball, basketball,
   // football and soccer
   const int candidate_array[] = { 14, 11, 30, 17 };
   const int team_array[]      = {  9,  5, 22, 11 };
   const int array_length = sizeof( candidate_array )
      / sizeof( candidate_array[0] );

   vector<int> candidate( candidate_array,
      candidate_array + array_length );
   vector<int> team( team_array, team_array + array_length );
   result.resize( array_length );

   // compute the number of possible teams
   transform( candidate.begin(), candidate.end(), team.begin(),
      result.begin(), teams );

   cout << endl
   << "There are " << result[0] << " possible baseball teams\n"
   << "There are " << result[1] << " possible basketball teams\n"
   << "There are " << result[2] << " possible football teams\n"
   << "There are " << result[3] << " possible soccer teams";
}

// n >= 0
int factorial( int n )
{
   int n_factorial = 1;
   for( int i = n; i > 1; --i )
      n_factorial *= i;

   return n_factorial;
}

// num_candidates >= 1,  1 <= team_size <= num_candidates
int teams( int num_candidates, int team_size )
{
   // use double to avoid integer overflow
   double permutations = 1;

   for( int i = num_candidates; i > num_candidates - team_size; --i )
      permutations *= i;

   for( int i = team_size; i > 1; --i )
      permutations /= i;

   return static_cast<int>( permutations );
}


Results

Factorials of 0-5: 1 1 2 6 24 120 

There are 2002 possible baseball teams
There are 462 possible basketball teams
There are 5852925 possible football teams
There are 12376 possible soccer teams


Maintained by John Loomis, updated Wed Feb 14 23:53:52 2007