1 Replies - 554 Views - Last Post: 04 March 2009 - 04:59 AM Rate Topic: -----

#1 erewnoh  Icon User is offline

  • D.I.C Head
  • member icon

Reputation: 17
  • View blog
  • Posts: 71
  • Joined: 01-March 09

Request a code check

Posted 04 March 2009 - 12:02 AM

So I bought Programming: Principles and Practice Using C++ to teach myself C++, and am working my way through an exercise.

I have the output I'm looking for, would just appreciate some pointers on ways to implement it more efficiently or on things that I've missed.

/*
 *  Permutation and Combination Calculator
 *
 *  This program will caclulate either the permutation or the combination of two user supplied numbers.
 *
 */

#include <iostream>
#include <string>
#include <math.h>

using namespace std;


double factorial (double val)
{
	if ((val==1) || (val == 0))
	{
		return 1;
	}
	
	return factorial(val-1)*val;
}


double repititionPermutation(double total, double subset)
{
	return pow(total, subset);
}

double limitedPermutation(double total, double subset)
{
	double workingTotal = factorial(total);
	return workingTotal / factorial(total - subset);
}

double repititionCombination(double total, double subset)
{
	return (factorial(total + subset - 1) / (factorial(subset) * factorial(total - 1)));
}

double limitedCombination(double total, double subset)
{
	double reduce = limitedPermutation(total, subset);
	return reduce / factorial(subset);
}

int main()
{
	char ch, yesNo;
	int total, subset;
	bool allowRepitition = false;
	
	cout << "This program will determine either the combination or permutation of set of user supplied values."
	<< " Please enter 'P' for permutation, or 'C' for combination. Also specify whether you would like to allow"
	<< " repitition (y/n)\n->";
	
	cin >> ch >> yesNo;
	
	if (yesNo == 'y' || yesNo == 'Y')
	{
		allowRepitition = true;
	}
	
	cout << " Please enter two whole numbers separated by a space. (e.g. 60 3) \n";
	cin >> total >> subset;
	
	
	switch (ch)
	{
		case 'P':
		case 'p':
			if (allowRepitition)
			{
				cout << repititionPermutation(total, subset);
			}
			else
			{
				cout << limitedPermutation(total, subset);
			}
			break;
		case 'C':
		case 'c':
			if (allowRepitition)
			{
				cout << repititionCombination(total, subset) << endl;
			}
			else
			{
				cout << limitedCombination(total, subset) << endl;
			}
			break;
		default:
			cout << "Please ensure you are using the proper input!";
			break;
	}
	
	return 0;
	
}



Appreciate any replies.

Is This A Good Question/Topic? 0
  • +

Replies To: Request a code check

#2 JackOfAllTrades  Icon User is offline

  • Saucy!
  • member icon

Reputation: 6062
  • View blog
  • Posts: 23,514
  • Joined: 23-August 08

Re: Request a code check

Posted 04 March 2009 - 04:59 AM

Without regard to the math involved (I'm very rusty there), it looks good to me. It's recursion city, baby! :)
Was This Post Helpful? 0
  • +
  • -

Page 1 of 1