Week #14 Challenge: C++

  • (5 Pages)
  • +
  • 1
  • 2
  • 3
  • 4
  • 5

67 Replies - 29126 Views - Last Post: 13 October 2010 - 08:11 AM

#31 Raynes  Icon User is offline

  • D.I.C Lover
  • member icon

Reputation: 611
  • View blog
  • Posts: 2,815
  • Joined: 05-January 09

Re: Week #14 Challenge: C++

Posted 06 April 2010 - 07:47 PM

I finally finished the pangram checker. Most painful thing I've ever done in my life. @_@.

If I ever pass kidney stones, I'll let you know how it compares.

The beast is unleashed:

#include <iostream>
using namespace std;

int main()
{
  char x[27];
  char c = 'a';

  for (int i = 0; i < 26; i++) 
    {
    x[i] = c;
    c++;
    }
  
  string str;
  cout << "Please enter a string: ";
  getline(cin, str);
  bool pangram = false;

  for(int i = 0; i < str.length(); i++)
    {
      str[i] = tolower(str[i]);
    }

  for(int i = 0; i < 26; i++) 
    {
    if (str.find(x[i]) == -1)
      {  
      pangram = true;
      break;
      }
    }
  
  if(pangram)
    cout << "The string you entered is not a pangram.";
  else
    cout << "The string you entered is indeed a pangram.";
  return 0;
}


This post has been edited by Raynes: 07 April 2010 - 01:01 AM

Was This Post Helpful? 3
  • +
  • -

#32 Tethik  Icon User is offline

  • D.I.C Head

Reputation: 17
  • View blog
  • Posts: 61
  • Joined: 14-March 10

Re: Week #14 Challenge: C++

Posted 06 April 2010 - 07:52 PM

My wall of text piglatin translator/whatever; all in one file for extra laziness. Mainly just playing around. Haven't sorted out the punctuation yet.

#include <iostream>
#include <vector>
#include <string>
#include <fstream>

using namespace std;



class Letter
{
private:
	char val;

public:
	Letter() { }
	Letter(char in) { val = in; }
	bool isVowel()
	{
		if(val == 'a' ||val == 'e' ||val == 'i' ||val == 'o' ||val == 'u') return true;
		else if(val == 'A' ||val == 'E' ||val == 'I' ||val == 'O' ||val == 'U') return true;
		return false;

	};
	bool isConsonant()
	{
		return !isVowel();
	};

	void set(char in)
	{
		val = in;
	}

	void operator=(char in)
	{
		val = in;
	}

	void operator=(Letter in)
	{
		val = in.val;
	}

	void show(ostream &os)
	{
		os << val;
	}

	char get()
	{
		return val;
	}

	void toLower()
	{
		if((int)val > 64 && (int)val < 91)
		{
			val += 32;
		}
	};

	void toUpper()
	{
		if((int)val > 96 && (int)val < 123)
		{
			val -= 32;
		}

	};

};

class Punctuation : public Letter
{
private:
	int behind_word;
	bool front;

public:
	Punctuation(char in, int bh) : Letter(in)
	{
		behind_word = bh;
		front = false;
	}	
	
	Punctuation(char in, int bh, bool w) : Letter(in)
	{
		behind_word = bh;
		front = w;
	}

	int geti() { return behind_word; }



};



class Word
{
private:
	vector<Letter> Letters;
	
public:
	void toPigLatin()
	{
		//Get first consonant
		unsigned int i = 0;
		for(;i < Letters.size() && Letters[i].isVowel(); i++) {}
		//Stops at first consonant (since its not a vowel)
		if(Letters.size() > 0)
		{

			if(Letters[0].isConsonant())
			{
				set(get() + Letters[0].get() + "ay");
				vector<Letter>::iterator _it = Letters.begin();
				Letters.erase(_it);
				_it = Letters.begin();
			}
			else if(Letters[0].isVowel())
			{
				set(get() + "way");
			}
			
		}
		
	};
	void fromPigLatin()
	{

		if(Letters.size() > 3)
		{
			//Remove ay
			vector<Letter>::iterator _it = Letters.end() - 1;
			Letters.erase(_it);
			_it = Letters.end() - 1;
			Letters.erase(_it);
			
			//Get consonant that was moved.
			_it = Letters.end() - 1;

			if(_it->get() != 'w')
			{			
			
				Letters.insert(Letters.begin(), *_it);
				_it = Letters.end() - 1;

			}
			Letters.erase(_it);
		}
		

	};

	void capitalize()
	{
		Letters[0].toUpper();
	};

	void toLower()
	{
		for(unsigned int i = 0; i < Letters.size(); i++)
			Letters[i].toLower();
	};
	void set(string in)
	{
		Letters.clear();

		for(unsigned int i = 0; i < in.length(); i++)
		{
			Letter z = in[i];		
			Letters.push_back(z);
		}

	};
	void show(ostream &os)
	{
		for(unsigned int i = 0; i < Letters.size(); i++)
			Letters[i].show(os);

	}

	string get()
	{
		string out = "";
		for(unsigned int i = 0; i < Letters.size(); i++)
			out += Letters[i].get();

		return out;
	};

	void operator+=(const string &B)/>
	{
		set(get() + B)/>;
	};

	void operator+=(const char &B)/>
	{
		Letter c(B)/>;
		Letters.push_back(c);
		
	};

	void operator+=(Word &B)/>
	{
		set(get() + b.get());

	};

	void clear()
	{
		Letters.clear();
	};

	int size()
	{
		return Letters.size();
	}

};

class Sentence
{
private:
	vector<Word> Words;
	vector<Punctuation> Punct;


public:
	void show(ostream &os)
	{
		for(unsigned int i = 0; i < Words.size(); i++)
		{
			for(unsigned int p = 0; p < Punct.size() && Punct[p].geti() != i; p++)
			{				
			}

			if(i > 0) os << ' '; 
			Words[i].show(os);
			for(unsigned int p = 0; p < Punct.size(); p++)
			{
				if(Punct[p].geti() == i) os << Punct[p].get();
			}
		}

		

	}

	void capitalize()
	{
		toLower();
		Words[0].capitalize();
	};

	void toLower()
	{
		for(unsigned int i = 0; i < Words.size(); i++) Words[i].toLower();
	};


	void set(const string &a)
	{
		Word b;
		int p = 0;
		for(unsigned int i = 0; i < a.size(); i++)
		{
			if(a[i] == ' ' || a[i] == ',' || a[i] == ':' || a[i] == ';' || a[i] == '(' || a[i] == ')' || a[i] == '"' || a[i] == '/' || a[i] == '\'')
			{
				if(b.size() > 0) 
				{
					if(a[i] != ' ')
					{
						Punctuation poo(a[i], p);
						Punct.push_back(poo);
					}

					Words.push_back(B)/>;
					p++;
					b.clear();
				}
				continue;
			}

			b += a[i];

		}
		Words.push_back(B)/>;

		capitalize();

	}

	void toPigLatin()
	{
		for(unsigned int i = 0; i < Words.size(); i++)
			Words[i].toPigLatin();
		
		capitalize();
	}

	void fromPigLatin()
	{
		for(unsigned int i = 0; i < Words.size(); i++)
			Words[i].fromPigLatin();
		
		capitalize();
	}

};


class Text
{
private:
	vector<Sentence> Sentences;

public:
	void set(string in)
	{
		string b = "";
		for(unsigned int i = 0; i < in.length(); i++)
		{
			if(in[i] == '.' || in[i] == '!' || in[i] == '?')
			{
				Sentence a;
				a.set(B)/>;
				Sentences.push_back(a);
				b = "";
			}

			b += in[i];

		}

	}
	void set(ifstream &in)
	{
		string toset = "";
		string b;
		if(in.is_open())
		{
			while(!in.eof())
			{
				getline(in,B)/>;
				toset += b;
			}

		}

		set(toset);

	}

	void get(ofstream &of)
	{
		show(of);

	}
	void toPigLatin()
	{
		for(unsigned int i = 0; i < Sentences.size(); i++)
			Sentences[i].toPigLatin();
		
		capitalize();
	}

	void fromPigLatin()
	{
		for(unsigned int i = 0; i < Sentences.size(); i++)
			Sentences[i].fromPigLatin();
		
		capitalize();
	}

	void capitalize()
	{
		for(unsigned int i = 0; i < Sentences.size(); i++) Sentences[i].toLower();
		Sentences[0].capitalize();
	};

	void show(ostream &os)
	{
				for(unsigned int i = 0; i < Sentences.size(); i++) Sentences[i].show(os);

	}

};



int main()
{



		Text toyourmother;

		string b = "";
		cout << "What file to translate?" << endl;
		getline(cin,B)/>;
		ifstream input(b.c_str());
		toyourmother.set(input);
		
		toyourmother.toPigLatin();
		cout << "Save to:" << endl;
		getline(cin, B)/>;
		ofstream output(b.c_str());
		toyourmother.show(output);		

	


	system("pause");

}

Was This Post Helpful? 1
  • +
  • -

#33 Skaggles  Icon User is offline

  • THE PEN IS MIGHTIER
  • member icon





Reputation: 251
  • View blog
  • Posts: 640
  • Joined: 01-March 09

Re: Week #14 Challenge: C++

Posted 06 April 2010 - 08:02 PM

Here's my application. It's a simple console app that reads user input against an XML of possible input and responses. Basically, it's a simple chat bot. You can add more phrases to the XML file to make it smarter. Nothing real special, but I had fun messing around with it.

The XML parser isn't a true XML parser in the sense that I just look for the tags that I know will be there. I found myself really missing the ease of C# at times, but I also found it nice to get away from relying on .NET for everything.

Attached File  smartychat.zip (10.12K)
Number of downloads: 263
Attached File  smartychatsrc.zip (4.57K)
Number of downloads: 237
Was This Post Helpful? 0
  • +
  • -

#34 timkd127  Icon User is offline

  • D.I.C Head

Reputation: 2
  • View blog
  • Posts: 74
  • Joined: 27-February 10

Re: Week #14 Challenge: C++

Posted 06 April 2010 - 08:14 PM

Ive been looking for a reason to go from c to c++, deffinitly doin this one
Was This Post Helpful? 0
  • +
  • -

#35 nmeans73  Icon User is offline

  • D.I.C Head

Reputation: 19
  • View blog
  • Posts: 59
  • Joined: 26-December 09

Re: Week #14 Challenge: C++

Posted 06 April 2010 - 09:51 PM

I wrote a random password generator a couple of months ago. It isn't too sophisticated but it may still be a little useful.

////////////////////////////////////////////////////////////////////
//Purpose: This program generates a pseudo random password of 
//         selected size and character composition.
////////////////////////////////////////////////////////////////////

#include <iostream>
#include <ctime>
#include <cstdlib>
#include <string>
#include <algorithm>
#include <fstream>


using namespace std;

//PROTOTYPES AND CONSTANTS

void getData(int& length, int& composition);
//Gets and validates the user inputted information on the password to be generated
void lowerCase(int length, ofstream& fout);
//generates a password of lowercase letters and displays it
void lowerAndUpperCase(int length, ofstream& fout);
//generates a password of lowercase and uppercase letters
void lowerUpperAndNum(int length, ofstream& fout);
//generates a password of lower/uppercase letters and numbers
void allOfTheAbove(int length, ofstream& fout);
//generates a password of lower/uppercase letters, numbers and symbols
void lowerAndNum(int length, ofstream& fout);
//generates a password of lowercase letters and numbers





int main()
{
	char selection;          //variable for user input on whether or not to run program again 
	int length, composition; //variables to hold the string length 
	                         //and composition of the password

	string destination;

	ofstream fout;

	srand(time(NULL));       //seeds the pseudo-random generator

	cout<<"Enter the path of where you would like the file saved to.\n\n"
		<<"For example: C:/Passwords.txt \n\n";
	getline(cin, destination);

	fout.open(destination.c_str());

	cout<<endl;

	while(!fout)
	{
		cout<<"ERROR!!!"<<endl<<endl;
		cout<<"Please enter a different path: ";
		getline(cin, destination);
		fout.open(destination.c_str());
	}


	do
	{//allows users to run the program multiple times
		getData(length, composition);

		if(composition == 1)
			lowerCase(length, fout);

		else if(composition == 2)
			lowerAndNum(length, fout);

		else if(composition == 3)
			lowerAndUpperCase(length, fout);

		else if(composition == 4)
			lowerUpperAndNum(length, fout);
	
		else if(composition == 5)
			allOfTheAbove(length, fout);


		cout<<"Would you like to generate another password (y or n)? ";
		cin>>selection;
		cout<<endl<<endl;

		while(selection != 'n' && selection != 'y')
		{
			cout<<"Your choice must either be y or n, try again: ";
			cin>> selection;
			cout<<endl<<endl;
		}

	}
	while(selection == 'y');

	cout<<endl;

	cout<<"Thank you and have a nice day. \n\n";

	fout.close();


	cin.ignore();
	cin.get();
	return 0;
}


//DEFINTIONS SECTION

void getData(int& length, int& composition)
{//function gets and validates the user input

	cout<<"How long would you like your password to be?\n"
		<<"(must be at least 5 characters long) ";
	cin >>length;
	cout<<endl;

	while(length <= 4)
	{
		cout<<"You entered an unexpected value. \n"
			<<"Please enter the length again: ";
		cin>>length;
		cout<<endl;
	}

	cout<<endl<<endl;

	cout<<"What types of characters would you like your password to be comprised of? \n";
	cout<<endl;
	cout<<"1. Lowercase letters \n"
		<<"2. Lowercase letters and Numbers \n"
		<<"3. Lowercase and Uppercase letters \n"
		<<"4. Lowercase letters, Uppercase letters and Numbers \n"
		<<"5. Lowercase letters, Uppercase letters, Numbers and Symbols \n\n";
	cin>>composition;
	cout<<endl<<endl;

	while(composition > 5 || composition < 1)
	{
		cout<<"That is an invalid choice, please select again: \n\n";
		cout<<"1. Lowercase letters \n"
			<<"2. Lowercase letters and Numbers \n"
			<<"3. Lowercase and Uppercase letters \n"
			<<"4. Lowercase letters, Uppercase letters and Numbers \n"
			<<"5. Lowercase letters, Uppercase letters, Numbers and Symbols \n\n";
		cin>>composition;
		cout<<endl<<endl;
	}

}

void lowerCase(int length, ofstream& fout)
{//generates a password of only lowercase characters and displays it

	char letter;            //letter to be placed in the vector

	string password;        //string to hold the password



	for(int i = 0; i < length; i++)
	{//builds the password

		letter = rand() % 25 + 97;

		password = password + letter;
	}

	for(int a=0; a<1000; a++)
	{//shufles the password string 1000 times

		random_shuffle(password.begin(), password.end());
	}


	cout<<"Your password is: "<<password<<endl<<endl;
	fout<<password<<endl<<endl;
	


}

void lowerAndUpperCase(int length, ofstream& fout)
{//generates a password of lower and upper case letters
 

	
	
	char upperCase, lowerCase;        //holds the random character of each case
	int numberCaps, numberLower;      //the total number of upper/lowercase letters to be generated

	string upper, lower, password;    //strings to hold the different characters


	numberCaps = rand() % length + 1; //initial number of capital letters

	//If the number of capital letters is too small, program will calculate a new number
	while(length > 2 && numberCaps < 2)
		numberCaps = rand() % length + 1;

	while(numberCaps >= ((2*length)/3))
		numberCaps = rand() % length + 1;

	while(numberCaps <= (length/3))
		numberCaps = rand() % length + 1;


	numberLower = length - numberCaps;  //number of lowercase letters is totally dependent on numberCaps


	for(int i=0; i < numberCaps; i++)
	{//generates uppercase letters
		upperCase = rand() % 25 + 65;

		upper = upper + upperCase;
	}

	for(int j=0; j < numberLower; j++)
	{//generates lowercase letters
		lowerCase = rand() % 25 +97;

		lower = lower + lowerCase;
	}


	password = lower+upper;

	for(int a=0; a<1000; a++)
	{//shuffles the password string 1000 times

		random_shuffle(password.begin(), password.end());	
	}

	cout<<"Your password is: "<<password<<endl<<endl;
	fout<<password<<endl<<endl;


}


void lowerUpperAndNum(int length, ofstream& fout)
{//generates a password of lower/uppercase letters and numbers

	
	char upperCase, lowerCase, randNumber;       //random upper/lowercase letters/number                 
	int numberUpper, numberLower, numberNumber;  //the total number of each character type
	int whatsLeft;                               //the amount of space left after the number of caps is determined

	string upper, lower, numbers, password;      //holds all the random numbers/letters and the final password

	
	numberUpper = rand() % length + 1;           //initial number of capital letters

	//If the number of capital letters is too small, program will calculate a new number
	while(length > 3 && numberUpper < 2)
		numberUpper = rand() % length + 1;

	while(numberUpper >= ((2*length)/3))
		numberUpper = rand() % length + 1;

	while(numberUpper <= (length/3))
		numberUpper = rand() % length + 1;

	whatsLeft = length - numberUpper;            //how many characters are left after the number of caps is known

	numberNumber = rand() % whatsLeft + 1;       //inital number of numbers in the password

	while(numberNumber >= ((2*whatsLeft)/3))
		numberNumber = rand() % whatsLeft + 1;

	while(numberNumber <= (whatsLeft/3))
		numberNumber = rand() % whatsLeft + 1;

	numberLower = length - (numberUpper+numberNumber);   //number of lowercase letters is totally dependent on numberCaps

	for(int a=0; a<numberUpper; a++)
	{//generates random capital letters

		upperCase = rand() % 25 + 65;

		upper = upper + upperCase;

	}

	for(int b=0; b<numberLower; b++)
	{//generates random lowercase letters

		lowerCase = rand() % 25 + 97;

		lower = lower + lowerCase;

	}

	for(int c=0; c<numberNumber; c++)
	{//generates random numbers

		randNumber = rand() % 9 + 48;
		
		numbers = numbers + randNumber;

	}


	password = numbers + lower + upper;

	for(int d=0; d<1000; d++)
	{//randomizes the combined strings 1000 times

		random_shuffle(password.begin(), password.end());
	}

	cout<<"Your password is: "<<password<<endl<<endl;
	fout<<password<<endl<<endl;
}


void allOfTheAbove(int length, ofstream& fout)
{//generates a random password from all the data types

	
	char upperCase, lowerCase, randNumber, symbol;             //random upper/lowercase letters/number/symbol                 
	int numberUpper, numberLower, numberNumber, numberSymbol;  //the total number of each character type
	int total;                                                 //the amount of space taken up by numberUpper-Symbol
	string upper, lower, numbers, symbols, password;           //holds all the random numbers/letters/symbols 
	                                                           //and the final password

	numberUpper = length/4;
	numberLower = length/4;
	numberNumber= length/4;
	numberSymbol= length/4;

	total = numberUpper + numberLower + numberNumber + numberSymbol; 

	if(total < length)                                        //checks to see if the total numbers matches the length
		numberSymbol = (length-total) + numberSymbol;		  //if the total is less than the length, the remaining 
	                                                          //characters will be more symbols



	for(int a=0; a<numberUpper; a++)
	{//generates random capital letters

		upperCase = rand() % 25 + 65;

		upper = upper + upperCase;

	}

	for(int b=0; b<numberLower; b++)
	{//generates random lowercase letters

		lowerCase = rand() % 25 + 97;

		lower = lower + lowerCase;

	}

	for(int c=0; c<numberNumber; c++)
	{//generates random numbers

		randNumber = rand() % 9 + 48;
		
		numbers = numbers + randNumber;

	}

	for(int d=0; d<numberSymbol; d++)
	{//generates random symbols

		symbol = rand() % 92 + 33;

		if(symbol >= 48 && symbol <= 57)
			symbol = rand() % 92 + 33;

		if(symbol >= 65 && symbol <= 90)
			symbol = rand() % 92 + 33;

		if(symbol >= 97 && symbol <= 122)
			symbol = rand() % 92 + 33;

		symbols = symbols + symbol;
	}

	password = numbers + symbols + lower + upper;

	for(int e=0; e<1000; e++)
	{//randomizes the password 1000 times

		random_shuffle(password.begin(), password.end());

	}

	cout<<"Your password is: "<<password<<endl<<endl;
	fout<<password<<endl<<endl;
	
}

void lowerAndNum(int length, ofstream& fout)
{
	char number, lower;              //number and lowercase letter characters
	int numberLower, numberNumber;	 //holds the total number of each char type

	string lowerCase, numberString, password;

	numberLower = rand() % length + 1;
	numberNumber = length - numberLower;

	for(int i = 0; i < numberLower; i++)
	{//generates random lowercase letters
		lower = rand() % 25 + 97;

		lowerCase = lowerCase + lower;

		
	}

	for(int j=0; j < numberNumber; j++)
	{//generates random numbers
		number = rand() % 9 + 48;

		numberString = numberString + number;

		
	}

	password = lowerCase + numberString;

	for(int a=0; a<1000; a++)
	{//shufles the password string 1000 times

		random_shuffle(password.begin(), password.end());
	}


	cout<<"Your password is: "<<password<<endl<<endl;
	fout<<password<<endl<<endl;

}
[\code]

I wrote a random password generator a couple of months ago. It isn't too sophisticated but it may still be a little useful.

[code]
////////////////////////////////////////////////////////////////////
//Purpose: This program generates a pseudo random password of 
//         selected size and character composition.
////////////////////////////////////////////////////////////////////

#include <iostream>
#include <ctime>
#include <cstdlib>
#include <string>
#include <algorithm>
#include <fstream>


using namespace std;

//PROTOTYPES AND CONSTANTS

void getData(int& length, int& composition);
//Gets and validates the user inputted information on the password to be generated
void lowerCase(int length, ofstream& fout);
//generates a password of lowercase letters and displays it
void lowerAndUpperCase(int length, ofstream& fout);
//generates a password of lowercase and uppercase letters
void lowerUpperAndNum(int length, ofstream& fout);
//generates a password of lower/uppercase letters and numbers
void allOfTheAbove(int length, ofstream& fout);
//generates a password of lower/uppercase letters, numbers and symbols
void lowerAndNum(int length, ofstream& fout);
//generates a password of lowercase letters and numbers





int main()
{
	char selection;          //variable for user input on whether or not to run program again 
	int length, composition; //variables to hold the string length 
	                         //and composition of the password

	string destination;

	ofstream fout;

	srand(time(NULL));       //seeds the pseudo-random generator

	cout<<"Enter the path of where you would like the file saved to.\n\n"
		<<"For example: C:/Passwords.txt \n\n";
	getline(cin, destination);

	fout.open(destination.c_str());

	cout<<endl;

	while(!fout)
	{
		cout<<"ERROR!!!"<<endl<<endl;
		cout<<"Please enter a different path: ";
		getline(cin, destination);
		fout.open(destination.c_str());
	}


	do
	{//allows users to run the program multiple times
		getData(length, composition);

		if(composition == 1)
			lowerCase(length, fout);

		else if(composition == 2)
			lowerAndNum(length, fout);

		else if(composition == 3)
			lowerAndUpperCase(length, fout);

		else if(composition == 4)
			lowerUpperAndNum(length, fout);
	
		else if(composition == 5)
			allOfTheAbove(length, fout);


		cout<<"Would you like to generate another password (y or n)? ";
		cin>>selection;
		cout<<endl<<endl;

		while(selection != 'n' && selection != 'y')
		{
			cout<<"Your choice must either be y or n, try again: ";
			cin>> selection;
			cout<<endl<<endl;
		}

	}
	while(selection == 'y');

	cout<<endl;

	cout<<"Thank you and have a nice day. \n\n";

	fout.close();


	cin.ignore();
	cin.get();
	return 0;
}


//DEFINTIONS SECTION

void getData(int& length, int& composition)
{//function gets and validates the user input

	cout<<"How long would you like your password to be?\n"
		<<"(must be at least 5 characters long) ";
	cin >>length;
	cout<<endl;

	while(length <= 4)
	{
		cout<<"You entered an unexpected value. \n"
			<<"Please enter the length again: ";
		cin>>length;
		cout<<endl;
	}

	cout<<endl<<endl;

	cout<<"What types of characters would you like your password to be comprised of? \n";
	cout<<endl;
	cout<<"1. Lowercase letters \n"
		<<"2. Lowercase letters and Numbers \n"
		<<"3. Lowercase and Uppercase letters \n"
		<<"4. Lowercase letters, Uppercase letters and Numbers \n"
		<<"5. Lowercase letters, Uppercase letters, Numbers and Symbols \n\n";
	cin>>composition;
	cout<<endl<<endl;

	while(composition > 5 || composition < 1)
	{
		cout<<"That is an invalid choice, please select again: \n\n";
		cout<<"1. Lowercase letters \n"
			<<"2. Lowercase letters and Numbers \n"
			<<"3. Lowercase and Uppercase letters \n"
			<<"4. Lowercase letters, Uppercase letters and Numbers \n"
			<<"5. Lowercase letters, Uppercase letters, Numbers and Symbols \n\n";
		cin>>composition;
		cout<<endl<<endl;
	}

}

void lowerCase(int length, ofstream& fout)
{//generates a password of only lowercase characters and displays it

	char letter;            //letter to be placed in the vector

	string password;        //string to hold the password



	for(int i = 0; i < length; i++)
	{//builds the password

		letter = rand() % 25 + 97;

		password = password + letter;
	}

	for(int a=0; a<1000; a++)
	{//shufles the password string 1000 times

		random_shuffle(password.begin(), password.end());
	}


	cout<<"Your password is: "<<password<<endl<<endl;
	fout<<password<<endl<<endl;
	


}

void lowerAndUpperCase(int length, ofstream& fout)
{//generates a password of lower and upper case letters
 

	
	
	char upperCase, lowerCase;        //holds the random character of each case
	int numberCaps, numberLower;      //the total number of upper/lowercase letters to be generated

	string upper, lower, password;    //strings to hold the different characters


	numberCaps = rand() % length + 1; //initial number of capital letters

	//If the number of capital letters is too small, program will calculate a new number
	while(length > 2 && numberCaps < 2)
		numberCaps = rand() % length + 1;

	while(numberCaps >= ((2*length)/3))
		numberCaps = rand() % length + 1;

	while(numberCaps <= (length/3))
		numberCaps = rand() % length + 1;


	numberLower = length - numberCaps;  //number of lowercase letters is totally dependent on numberCaps


	for(int i=0; i < numberCaps; i++)
	{//generates uppercase letters
		upperCase = rand() % 25 + 65;

		upper = upper + upperCase;
	}

	for(int j=0; j < numberLower; j++)
	{//generates lowercase letters
		lowerCase = rand() % 25 +97;

		lower = lower + lowerCase;
	}


	password = lower+upper;

	for(int a=0; a<1000; a++)
	{//shuffles the password string 1000 times

		random_shuffle(password.begin(), password.end());	
	}

	cout<<"Your password is: "<<password<<endl<<endl;
	fout<<password<<endl<<endl;


}


void lowerUpperAndNum(int length, ofstream& fout)
{//generates a password of lower/uppercase letters and numbers

	
	char upperCase, lowerCase, randNumber;       //random upper/lowercase letters/number                 
	int numberUpper, numberLower, numberNumber;  //the total number of each character type
	int whatsLeft;                               //the amount of space left after the number of caps is determined

	string upper, lower, numbers, password;      //holds all the random numbers/letters and the final password

	
	numberUpper = rand() % length + 1;           //initial number of capital letters

	//If the number of capital letters is too small, program will calculate a new number
	while(length > 3 && numberUpper < 2)
		numberUpper = rand() % length + 1;

	while(numberUpper >= ((2*length)/3))
		numberUpper = rand() % length + 1;

	while(numberUpper <= (length/3))
		numberUpper = rand() % length + 1;

	whatsLeft = length - numberUpper;            //how many characters are left after the number of caps is known

	numberNumber = rand() % whatsLeft + 1;       //inital number of numbers in the password

	while(numberNumber >= ((2*whatsLeft)/3))
		numberNumber = rand() % whatsLeft + 1;

	while(numberNumber <= (whatsLeft/3))
		numberNumber = rand() % whatsLeft + 1;

	numberLower = length - (numberUpper+numberNumber);   //number of lowercase letters is totally dependent on numberCaps

	for(int a=0; a<numberUpper; a++)
	{//generates random capital letters

		upperCase = rand() % 25 + 65;

		upper = upper + upperCase;

	}

	for(int b=0; b<numberLower; b++)
	{//generates random lowercase letters

		lowerCase = rand() % 25 + 97;

		lower = lower + lowerCase;

	}

	for(int c=0; c<numberNumber; c++)
	{//generates random numbers

		randNumber = rand() % 9 + 48;
		
		numbers = numbers + randNumber;

	}


	password = numbers + lower + upper;

	for(int d=0; d<1000; d++)
	{//randomizes the combined strings 1000 times

		random_shuffle(password.begin(), password.end());
	}

	cout<<"Your password is: "<<password<<endl<<endl;
	fout<<password<<endl<<endl;
}


void allOfTheAbove(int length, ofstream& fout)
{//generates a random password from all the data types

	
	char upperCase, lowerCase, randNumber, symbol;             //random upper/lowercase letters/number/symbol                 
	int numberUpper, numberLower, numberNumber, numberSymbol;  //the total number of each character type
	int total;                                                 //the amount of space taken up by numberUpper-Symbol
	string upper, lower, numbers, symbols, password;           //holds all the random numbers/letters/symbols 
	                                                           //and the final password

	numberUpper = length/4;
	numberLower = length/4;
	numberNumber= length/4;
	numberSymbol= length/4;

	total = numberUpper + numberLower + numberNumber + numberSymbol; 

	if(total < length)                                        //checks to see if the total numbers matches the length
		numberSymbol = (length-total) + numberSymbol;		  //if the total is less than the length, the remaining 
	                                                          //characters will be more symbols



	for(int a=0; a<numberUpper; a++)
	{//generates random capital letters

		upperCase = rand() % 25 + 65;

		upper = upper + upperCase;

	}

	for(int b=0; b<numberLower; b++)
	{//generates random lowercase letters

		lowerCase = rand() % 25 + 97;

		lower = lower + lowerCase;

	}

	for(int c=0; c<numberNumber; c++)
	{//generates random numbers

		randNumber = rand() % 9 + 48;
		
		numbers = numbers + randNumber;

	}

	for(int d=0; d<numberSymbol; d++)
	{//generates random symbols

		symbol = rand() % 92 + 33;

		if(symbol >= 48 && symbol <= 57)
			symbol = rand() % 92 + 33;

		if(symbol >= 65 && symbol <= 90)
			symbol = rand() % 92 + 33;

		if(symbol >= 97 && symbol <= 122)
			symbol = rand() % 92 + 33;

		symbols = symbols + symbol;
	}

	password = numbers + symbols + lower + upper;

	for(int e=0; e<1000; e++)
	{//randomizes the password 1000 times

		random_shuffle(password.begin(), password.end());

	}

	cout<<"Your password is: "<<password<<endl<<endl;
	fout<<password<<endl<<endl;
	
}

void lowerAndNum(int length, ofstream& fout)
{
	char number, lower;              //number and lowercase letter characters
	int numberLower, numberNumber;	 //holds the total number of each char type

	string lowerCase, numberString, password;

	numberLower = rand() % length + 1;
	numberNumber = length - numberLower;

	for(int i = 0; i < numberLower; i++)
	{//generates random lowercase letters
		lower = rand() % 25 + 97;

		lowerCase = lowerCase + lower;

		
	}

	for(int j=0; j < numberNumber; j++)
	{//generates random numbers
		number = rand() % 9 + 48;

		numberString = numberString + number;

		
	}

	password = lowerCase + numberString;

	for(int a=0; a<1000; a++)
	{//shufles the password string 1000 times

		random_shuffle(password.begin(), password.end());
	}


	cout<<"Your password is: "<<password<<endl<<endl;
	fout<<password<<endl<<endl;

}


Was This Post Helpful? 1
  • +
  • -

#36 sarmanu  Icon User is offline

  • D.I.C Lover
  • member icon

Reputation: 966
  • View blog
  • Posts: 2,362
  • Joined: 04-December 09

Re: Week #14 Challenge: C++

Posted 07 April 2010 - 12:36 AM

@ Raynes: the logic of the program is indeed correct, but you need to have the header <string> included, otherwise you will get a compilation error. With the header I told you about it works, but there are two things you should consider though:
1. it makes more sense to assign "false" to "pangram", when this instruction executes:
if (str.find(x[i]) == -1)


2. you should add a "break" statement when that above instruction executes, as there is no need to loop anymore, since we didn't find the needed letter.
Was This Post Helpful? 1
  • +
  • -

#37 Raynes  Icon User is offline

  • D.I.C Lover
  • member icon

Reputation: 611
  • View blog
  • Posts: 2,815
  • Joined: 05-January 09

Re: Week #14 Challenge: C++

Posted 07 April 2010 - 12:58 AM

I didn't get any compilation errors. Just double checked. Works fine. As for the rest of it, I don't intend to ever touch this code again, but it's nice to know that I might have done it right. Is there a better way to do a pangram checker? It feels absolutely monolithic. :|

EDIT: Also, I think the break you speak off was accidentally removed during some restructuring. Thanks for pointing that out.

EDIT2: I found this: http://rosettacode.o...checker#C.2B.2B

Much less monolithic, but still pretty monolithic compared to what I'm used to. This challenge was great, if only for the orgasmic joy I felt once I actually got that damn program working. :D

This post has been edited by Raynes: 07 April 2010 - 01:20 AM

Was This Post Helpful? 0
  • +
  • -

#38 sarmanu  Icon User is offline

  • D.I.C Lover
  • member icon

Reputation: 966
  • View blog
  • Posts: 2,362
  • Joined: 04-December 09

Re: Week #14 Challenge: C++

Posted 07 April 2010 - 01:18 AM

Eww, what Compiler are you using? Because std::getline and std::string are both defined in <string>. For example, your program does not compile on MSVC 2008 because it complains about not finding std::getline and string.
Was This Post Helpful? 0
  • +
  • -

#39 Raynes  Icon User is offline

  • D.I.C Lover
  • member icon

Reputation: 611
  • View blog
  • Posts: 2,815
  • Joined: 05-January 09

Re: Week #14 Challenge: C++

Posted 07 April 2010 - 01:23 AM

I'm using G++.
Was This Post Helpful? 0
  • +
  • -

#40 Huzi94  Icon User is offline

  • D.I.C Head
  • member icon

Reputation: 14
  • View blog
  • Posts: 119
  • Joined: 14-November 09

Re: Week #14 Challenge: C++

Posted 07 April 2010 - 03:16 AM

Hello,
Here is a simple messagebox generator that uses Windows API.
#include <windows.h>
#include <string>
#include <sstream>
using namespace std;

/*Define resources*/
#define   TitleEditId       200
#define   MessageEditId     201
#define   ResultEditId      202
#define   ButtonId          203
#define   CopyButtonId      204
#define   BreakButtonId     205
#define   ComboBox          206
#define   ResetButtonId     207
#define   IDC_TEXT          208

HINSTANCE hThisInstance;
HFONT  prog_font = CreateFont(18,0,0,0,FW_BOLD,0,0,0,ANSI_CHARSET,OUT_DEFAULT_PRECIS,CLIP_DEFAULT_PRECIS,DEFAULT_QUALITY,FF_MODERN,"Tahoma");
HBRUSH TextBrush;
HWND hwnd;

string MessageBox(string title, string message, string flag) {
	stringstream ss;
	ss << "MessageBox(0, \"" << message << "\", \"" << title << "\", MB_OK" << flag << ");";
	return ss.str();
}

bool isEmpty(HWND hwnd) {
	char title[255]; 
	GetDlgItemText(hwnd, TitleEditId, title, 255);
	int s=strlen(title);
	return (s!=0);
}
/*  Declare Windows procedure  */
LRESULT CALLBACK WindowProcedure (HWND, UINT, WPARAM, LPARAM);

/*  Make the class name into a global variable  */
char szClassName[ ] = "WindowsApp";

int WINAPI WinMain (HINSTANCE hThisInstance,
					HINSTANCE hPrevInstance,
					LPSTR lpszArgument,
					int nFunsterStil)

{
	HWND hwnd;               /* This is the handle for our window */
	MSG messages;            /* Here messages to the application are saved */
	WNDCLASSEX wincl;        /* Data structure for the windowclass */

	/* The Window structure */
	wincl.hInstance = hThisInstance;
	wincl.lpszClassName = szClassName;
	wincl.lpfnWndProc = WindowProcedure;      /* This function is called by windows */
	wincl.style = CS_DBLCLKS;                 /* Catch double-clicks */
	wincl.cbSize = sizeof (WNDCLASSEX);

	/* Use default icon and mouse-pointer */
	wincl.hIcon = LoadIcon (NULL, IDI_APPLICATION);
	wincl.hIconSm = LoadIcon (NULL, IDI_APPLICATION);
	wincl.hCursor = LoadCursor (NULL, IDC_ARROW);
	wincl.lpszMenuName = NULL;                 /* No menu */
	wincl.cbClsExtra = 0;                      /* No extra bytes after the window class */
	wincl.cbWndExtra = 0;                      /* structure or the window instance */
	/* Use Windows's default color as the background of the window */
	wincl.hbrBackground =  CreateSolidBrush(RGB(210, 255, 255));

	/* Register the window class, and if it fails quit the program */
	if (!RegisterClassEx (&wincl))
		return 0;

	/* The class is registered, let's create the program*/
	hwnd = CreateWindowEx (
		0,                   /* Extended possibilites for variation */
		szClassName,         /* Classname */
		"MessageBox Generator",       /* Title Text */
		WS_VISIBLE | WS_POPUP |WS_CAPTION | WS_BORDER | WS_SYSMENU, /* default window */
		CW_USEDEFAULT,       /* Windows decides the position */
		CW_USEDEFAULT,       /* where the window ends up on the screen */
		544,                 /* The programs width */
		305,                 /* and height in pixels */
		NULL,                /* The window is a child-window to desktop */
		NULL,                /* No menu */
		hThisInstance,       /* Program Instance handler */
		NULL                 /* No Window Creation data */
		);

	/* Make the window visible on the screen */
	ShowWindow (hwnd, nFunsterStil);

	/* Run the message loop. It will run until GetMessage() returns 0 */
	while(GetMessage(&messages,NULL,0,0))
	{
		HWND hActiveWindow = GetActiveWindow();
		if(!IsWindow(hActiveWindow) || !IsDialogMessage(hActiveWindow,&messages))
		{
			TranslateMessage(&messages);
			DispatchMessage(&messages);
		}
	}

	/* The program return-value is 0 - The value that PostQuitMessage() gave */
	return messages.wParam;
}
LRESULT CALLBACK WindowProcedure (HWND hwnd, UINT message, WPARAM wParam, LPARAM lParam)
{
	switch (message)                  /* handle the messages */
	{
	case WM_CREATE:
		/*Title TextBox*/
		CreateWindowEx(WS_EX_CLIENTEDGE,
			"EDIT",
			"",
			WS_CHILD | WS_VISIBLE | ES_AUTOHSCROLL | WS_TABSTOP | WS_GROUP,
			5, 5, 150, 20,
			hwnd,
			(HMENU)(TitleEditId),
			hThisInstance,
			0);
		/*Message TextBox*/
		CreateWindowEx(WS_EX_CLIENTEDGE,
			"EDIT",
			"",
			WS_CHILD | WS_VISIBLE | ES_AUTOHSCROLL | WS_TABSTOP ,
			5, 50, 350, 20,
			hwnd,
			(HMENU)MessageEditId,
			hThisInstance,
			0);
		/*Combo Box*/
		CreateWindow("COMBOBOX",
			0,
			WS_CHILD | WS_VISIBLE | CBS_DROPDOWN | CBS_DROPDOWNLIST | WS_TABSTOP,
			5, 95, 200, 100,
			hwnd,
			(HMENU)(ComboBox),
			hThisInstance,
			0);
		/*Result Textbox*/
		CreateWindowEx(WS_EX_CLIENTEDGE,
			"EDIT",
			"",
			WS_CHILD | WS_VISIBLE | WS_VSCROLL | ES_MULTILINE | ES_AUTOVSCROLL,
			5, 140, 350, 50,
			hwnd,
			(HMENU)ResultEditId,
			hThisInstance,
			0);
		/*Button*/
		CreateWindow("BUTTON",
			"Generate",
			WS_CHILD | WS_VISIBLE | WS_TABSTOP | BS_PUSHBUTTON,
			5, 210, 120, 30,
			hwnd,
			(HMENU )ButtonId,
			hThisInstance,
			0);
		/*Copy Buutton*/
		CreateWindow("BUTTON",
			"Copy",
			WS_CHILD | WS_VISIBLE | WS_TABSTOP,
			365, 150, 120, 30,
			hwnd,
			(HMENU )CopyButtonId,
			hThisInstance,
			0);
		/*Break Buutton*/
		CreateWindow("BUTTON",
			"/n",
			WS_CHILD | WS_VISIBLE | WS_TABSTOP,
			365, 50, 40, 25,
			hwnd,
			(HMENU )BreakButtonId,
			hThisInstance,
			0);
		CreateWindow("BUTTON",
			"Reset",
			WS_CHILD | WS_VISIBLE | WS_TABSTOP,
			365, 210, 120, 30,
			hwnd,
			(HMENU )ResetButtonId,
			hThisInstance,
			0);
		CreateWindow("STATIC",
			"",
			WS_CHILD | WS_VISIBLE | WS_TABSTOP,
			5, 250, 260, 20,
			hwnd,
			(HMENU) IDC_TEXT,
			hThisInstance,
			0);
		//Set defaults
		SendMessage(GetDlgItem(hwnd,IDC_TEXT),WM_SETFONT,(WPARAM)prog_font,0);
		EnableWindow((GetDlgItem(hwnd,CopyButtonId)), FALSE);
		SendDlgItemMessage(hwnd, ComboBox, CB_ADDSTRING, 0, (LPARAM )"None");             	
		SendDlgItemMessage(hwnd, ComboBox, CB_ADDSTRING, 0, (LPARAM )"MB_ICONINFORMATION");
		SendDlgItemMessage(hwnd, ComboBox, CB_ADDSTRING, 0, (LPARAM )"MB_ICONEXCLAMATION");
		SendDlgItemMessage(hwnd, ComboBox, CB_SETCURSEL, 0, (LPARAM )"None");
		TextBrush = CreateSolidBrush(RGB(210, 255, 255));

		break;
	case WM_SETFOCUS:
		SetFocus(GetDlgItem(hwnd, TitleEditId));
		break;
	case WM_CTLCOLORSTATIC:
		{
			HDC dc = (HDC )wParam;
			SetBkMode(dc, TRANSPARENT);
			SetTextColor(dc, RGB(255, 0, 0));
			return (LRESULT )TextBrush;
		}
		break;
	case WM_COMMAND:
		{
			switch(wParam)
			{
			case ButtonId:
				{
					char message[255], title[255];
					char Buffer[255];
					string flag;
					char *i=" | ";
					if(!SendDlgItemMessage(hwnd, ComboBox, CB_GETCURSEL, 0, (LPARAM )"None"))
					{
						flag="";
					}
					else if(!GetDlgItemText(hwnd, ComboBox, Buffer, sizeof(Buffer)))
					{
						flag="";
					}
					else
					{
						stringstream ss;
						ss << i << Buffer;
						flag=ss.str();
					}
					if(!GetDlgItemText(hwnd, TitleEditId, title, 255) && !GetDlgItemText(hwnd, MessageEditId, message, 255))
						SendDlgItemMessage(hwnd,IDC_TEXT,WM_SETTEXT,0,(LPARAM)"Please enter a title and a message!");
					else if(!GetDlgItemText(hwnd, TitleEditId, title, 255))
						SendDlgItemMessage(hwnd,IDC_TEXT,WM_SETTEXT,0,(LPARAM)"Please enter a title!");
					else if(!GetDlgItemText(hwnd, MessageEditId, message, 255))
						SendDlgItemMessage(hwnd,IDC_TEXT,WM_SETTEXT,0,(LPARAM)"Please enter a message!");
					else
					{
						string result=MessageBox(title, message, flag);
						SetDlgItemText(hwnd, ResultEditId, result.c_str());
						SendDlgItemMessage(hwnd,IDC_TEXT,WM_SETTEXT,0,(LPARAM)"");
						EnableWindow((GetDlgItem(hwnd,CopyButtonId)), TRUE);
						EnableWindow((GetDlgItem(hwnd,ResetButtonId)), TRUE);
					}
					//()
					return 0;
				}
				break;
			case CopyButtonId:
				SendMessage(GetDlgItem(hwnd, ResultEditId),WM_COPY,0,0);
				break;
			case BreakButtonId:
				char message[255];
				int i;
				i=5;
				char A[2048];
				GetDlgItemText(hwnd, MessageEditId, message, 255);
				strcpy(A,message);
				sprintf(A,"%s%s",A,"\\n");
				SetDlgItemText(hwnd, MessageEditId, A);
				break;
			case ResetButtonId:
				if(isEmpty(hwnd)) {
					SetDlgItemText(hwnd, TitleEditId, "");
					SetDlgItemText(hwnd, MessageEditId, "");
					SetDlgItemText(hwnd, ResultEditId, "");
					SendDlgItemMessage(hwnd, ComboBox, CB_SETCURSEL, 0, (LPARAM )"None");
					EnableWindow((GetDlgItem(hwnd,CopyButtonId)), FALSE);
				}
				else { 
					MessageBox(0, "Nothing to reset", "Error", MB_OK | MB_ICONEXCLAMATION);
				}
				break;
			}
		}
		break;
	case WM_DESTROY:
		PostQuitMessage (0);       /* send a WM_QUIT to the message queue */
		break;
	default:                      /* for messages that we don't deal with */
		return DefWindowProc (hwnd, message, wParam, lParam);
	}

	return 0;
}


Was This Post Helpful? 1
  • +
  • -

#41 Kohana  Icon User is offline

  • D.I.C Head

Reputation: 22
  • View blog
  • Posts: 56
  • Joined: 09-January 10

Re: Week #14 Challenge: C++

Posted 07 April 2010 - 06:37 AM

C++ Tower Defence Game

My program although not perfect is a Tower Defence game that runs in the console. It gives something to look at but is ultimately just a demonstration of how c++ is used with regards to "objects".....the very thing that makes it C++.

Here you will find base and derived classes, use of pointers, memory allocation, OO programming, design pattern "Iterator" etc etc

The project shows base class Unit deriving two classes, Unit & Tower. The Map class is exactly that and the Cell class basically lets just adjust Cells within the Map. Such as pointing a Cell at a Tower or Tank to represent something is ocupying the cell.

Towers will attack and destroy anything in its North, East, South and West lines of site for 1 square.

There is no advanced path finding such as A* or any kind of targeting algorithm here.

Adding objects that can read and write to text files to save game state or just simply labelling the axis are just a few of the improvements I could add but alas time is not on my side.

Have a play with it & Good Luck everybody

Kohana

/////////////////////////////////////////////////////////////////////////////////////////
//
// File: Main.h
// Author: 
// Description: This file is the main menu for the game engine. It allows a user
//				to control some aspects of the game.
//
//
// Method: RunGame
// Arguments: None
// Return: Nothing
// Description: This Function controls the main menu and handles user input. All other
//				methods shall be called from within this class.
// Precondition: None
// Postcondition: The console now displays the main menu and will call
//				  appropriate methods for users input.
//
/////////////////////////////////////////////////////////////////////////////////////////

#include "Map.h"
#include <vector>
#include <iostream>
#include "Tower.h"
#include "Tank.h"
#include <algorithm>
#include <windows.h>

void RunGame();

int main() {
	// Run the game
	RunGame();	

	// Return exit success code
	return 0;
}

void RunGame() {
	// Used for menu control
	bool hasExited = false;
	int selected;
	int x, y;
	std::vector<Unit*> Units;
	std::vector<Unit*> Towers;
	

	// Create the game map
	Map gameMap(5, 5);

	while (hasExited == false) {
		gameMap.DisplayMap();
		std::cout << "D.I.C Week #14 Challenge: C++" << std::endl;
		std::cout << "----------------------------------------" << std::endl;
		std::cout << "" << std::endl;
		std::cout << "0) Exit." << std::endl;
		std::cout << "1) Display Map." << std::endl;
		std::cout << "2) Place tower." << std::endl;
		std::cout << "3) Add Enemy." << std::endl;
		std::cout << "4) Cycle." << std::endl;
		std::cout << "" << std::endl;
		std::cout << "Make your selection > ";
		std::cin >> selected;
		std::cout << "" << std::endl;

		system("CLS");
		// Run Menu Option
		switch(selected) {
		case 0 :
			// Set exit to true
			hasExited = true;
			break;

		case 1 :
			// Display the game map
			gameMap.DisplayMap();
			break;

		case 2 :
			// Place a tower on the board then display map
			gameMap.DisplayMap();
			std::cout << std::endl;
			std::cout << "Please input the coord's of the tower." << std::endl;
			std::cin >> x >> y;
			Towers.push_back(new Tower(gameMap.GetCell(x,y),x,y));
			system("CLS");
			break;

		case 3:
			// For the purpose of testing
			// this will act as my key unit before
			// going into game sequance
			Units.push_back(new Tank());
			gameMap.SpawnUnit(Units.back());
			break;
		
		case 4:
			// Move all enemys on the board. Remove defeated enemys. Add points to player.
			// Minus enemy success limit. Check if limit is 0 to end game. Game will end when 
			// 10 enemys enter the Goal point 4 , 4
			for(int i=0; i<5; i++)
			{
				for(int j=0; j<Units.size();j++)
				{
				gameMap.MoveUnit(Units[j]);
				Sleep(150);
				gameMap.DisplayMap();
				system("CLS");
				};

				// Spawning units.
				Units.push_back(new Tank());
				gameMap.SpawnUnit(Units.back());

				// check for enemy reaching goal
				/*if(Units.back() == gameMap.easyPath.back())
				{
	
				};*/
			};
			break;
			
		default:
			break;
		}

		// Spacer
		std::cout << "" << std::endl;
	}

}


Map.h



#ifndef TDG_MAP_H
#define TDG_MAP_H

#include "Cell.h"
#include "vector"
#include <map>

class Map
{
	public:
		// Constructors / Destructor
		Map(void);
		Map(int width, int height);

		// 	Accessors
		Cell* GetCell(int row, int column);

		// Procedures
		void SpawnUnit(Unit* unit);
		void DisplayMap();
		void MoveUnit(Unit*);

	private:
		// Width of the game map
		int mWidth;
		// Height of the game map
		int mHeight;
		// Container for the game map's cells
		std::map<int, Cell> mCells;
		// Returns the cells 'number' used to represent a 2d coordinate as a linear value
		int GetCellNumber(int row, int column);
		// Easy vector path
		std::vector<Cell*> easyPath;
		std::vector<Cell*>::iterator PathIter;
};

#endif


Map.cpp

#include "Map.h"
#include <iostream>
#include "vector"
#include <algorithm>

Map::Map(void) {
}

// Constructor that defines the width and height of the map
Map::Map(int width, int height) {
	this->mWidth = width;
	this->mHeight = height;

	int currentCell;
	for(int i = 0; i < height; i++) {
		for(int j = 0; j < width; j++) {

			currentCell = this->GetCellNumber(i, j);
			this->mCells[currentCell] = Cell(i, j);
		}
	}
	// Hardcoded easy path
	this->easyPath.push_back(&this->mCells[this->GetCellNumber(0,0)]);
	this->easyPath.push_back(&this->mCells[this->GetCellNumber(0,1)]);
	this->easyPath.push_back(&this->mCells[this->GetCellNumber(1,1)]);
	this->easyPath.push_back(&this->mCells[this->GetCellNumber(1,2)]);
	this->easyPath.push_back(&this->mCells[this->GetCellNumber(2,2)]);
	this->easyPath.push_back(&this->mCells[this->GetCellNumber(2,3)]);
	this->easyPath.push_back(&this->mCells[this->GetCellNumber(3,3)]);
	this->easyPath.push_back(&this->mCells[this->GetCellNumber(3,4)]);
	this->easyPath.push_back(&this->mCells[this->GetCellNumber(4,4)]);

	/*this->PathIter = this->easyPath.begin();*/
}

// Accessors
Cell*
Map::GetCell(int row, int column) {
	return &this->mCells[this->GetCellNumber(row, column)];
}

// Procedures
void
Map::DisplayMap() {
	std::map<int,Cell>::iterator mapIter = this->mCells.begin();
	int count=1;
	while(mapIter != this->mCells.end())
	{
		mapIter->second.DisplayContents();
		mapIter++;
		if(count == 5 || count == 10 || count == 15 || count == 20)
		{
			std::cout << std::endl;
		}
		count++;
	}
	std::cout << std::endl;
}

void 
Map::SpawnUnit(Unit* unit) {
	unit->setCell(*easyPath.begin(), unit);
}

void
Map::MoveUnit(Unit* unit) {
	Cell* temp;
	int i=0;
	// Get units cell location
	temp = unit->GetCell(unit);

	this->PathIter = this->easyPath.begin();

	while(temp != *PathIter)
	{
		PathIter++;
	}

	// Iterator is equal to current position
	PathIter++;

	// iterate position & set cell
	unit->setCell(*PathIter, temp, unit);
}

// Returns the cells 'number', used to represent a 2d coordinate as a linear value
int
Map::GetCellNumber(int row, int column) {
	if(row > this->mHeight || column > this->mWidth) {
		std::cout << "Cell Index Out Of Range!!";
		return 0;
	}
	else
		return this->mWidth * row + column;
}


Cell.h
#ifndef TDG_CELL_H
#define TDG_CELL_H

#include "Unit.h"

// Forward Declaration
class Unit;

class Cell
{
	public:
		// Constructors / Destructor
		Cell(void);
		Cell(int x, int y);

		// Procedures
		// Output the Units information
		void DisplayContents();
		void setUnit(Cell* cell, Unit* unit);
		Unit* GetUnit();
		void SetUnit();

	private:
		// The Unit that occupies this cell
		Unit* mUnit;
};

#endif



Cell.cpp
#include "Cell.h"

#include <iostream>

Cell::Cell(void) {
	this->mUnit = 0;
}

Cell::Cell(int x, int y)
{
	this->mUnit = 0;
}

// Procedures
// Output the Units information
void
Cell::DisplayContents() {
	if(this->mUnit == 0)
		// If the Unit doesn't exist
		std::cout << "  -  ";
	else
		// If the Unit does exist
		this->mUnit->ShowInfo();		
}
void
Cell::setUnit(Cell* cell, Unit* unit)
{
	mUnit = unit;
}
Unit*
Cell::GetUnit()
{
	return mUnit;
}
void
Cell::SetUnit()
{
	mUnit=0;
}


Unit.h
#ifndef TDG_UNIT_H
#define TDG_UNIT_H

#include "Cell.h"

// Forward Declaration
class Cell;

class Unit
{
	public:
		// Constructors / Destructor
		Unit(void);

		// Procedures
		virtual void ShowInfo()=0;
		virtual void setCell(Cell* cell, Unit* unit);
		void setCell(Cell* cell, Cell* currentPosition, Unit* unit);
		void setXY(int x, int y);

		// Accessors
		Cell* GetCell(Unit* unit);

	private:
		// Pointer to the cell the unit is occupying
		Cell* mCell;
		int X,Y;
};

#endif


Unit.cpp
#include "Unit.h"
#include "Tower.h"
#include "Cell.h"


Unit::Unit(void) {
	this->mCell = 0;
}
void Unit::setCell(Cell *cell, Unit* unit)
{
	this->mCell = cell;

	cell->setUnit(cell, unit);
}
void Unit::setCell(Cell *cell, Cell *currentPosition, Unit *unit)
{

	currentPosition->SetUnit();

	this->mCell = cell;

	cell->setUnit(cell, unit);
}

Cell* Unit::GetCell(Unit* unit) {
	return unit->mCell;
}

void Unit::setXY(int x, int y)
{
	this->X=x;
	this->Y=y;
}


Tank.h
#pragma once
#include "unit.h"

class Tank :
	public Unit
{
public:
	Tank(void);
	~Tank(void);
	Tank(Cell* cell);

	void ShowInfo();
};


Tank.cpp
#include "Tank.h"
#include<iostream>

Tank::Tank(void)
{
}

Tank::~Tank(void)
{
}
Tank::Tank(Cell* cell)
{
	this->setCell(cell, this);
}
void Tank::ShowInfo()
{
	std::cout << "  E  ";
}


Tower.h
#pragma once
#include "unit.h"

class Tower :
	public Unit
{
public:
	Tower(void);
	Tower(Cell*,int x,int y);
	~Tower(void);

	void ShowInfo();
};


Tower.cpp
#include "Tower.h"
#include "Unit.h"
#include <iostream>

Tower::Tower(void)
{
}
Tower::~Tower(void)
{
}
Tower::Tower(Cell* cell, int x, int y)
{
	this->setCell(cell, this);
	setXY(x,y);
}
void Tower::ShowInfo()
{
	std::cout << "  T  ";
}




Phew I don't think I missed anything. You should have something like below.

Posted Image

Good Luck Again

This post has been edited by Kohana: 07 April 2010 - 09:03 AM

Was This Post Helpful? 3
  • +
  • -

#42 sarmanu  Icon User is offline

  • D.I.C Lover
  • member icon

Reputation: 966
  • View blog
  • Posts: 2,362
  • Joined: 04-December 09

Re: Week #14 Challenge: C++

Posted 07 April 2010 - 06:53 AM

Windows: checks if you are connected to Internet, using GetIpForwardTable from <iphlapi.h>
#include <windows.h>
#include <iphlpapi.h>

#pragma comment(lib, "iphlpapi.lib")

BOOL InternetAvailable()
{
	typedef unsigned char uchar;
	DWORD size = 0;

	GetIpForwardTable(NULL, &size, false);
	uchar *bytes = new uchar[size];

	PMIB_IPFORWARDTABLE ft = *reinterpret_cast<PMIB_IPFORWARDTABLE *>(&bytes);
	if (ft == NULL)
		exit(EXIT_FAILURE);

	if (GetIpForwardTable(ft, &size, FALSE) == NO_ERROR)
	{
		DWORD r_count = ft->dwNumEntries;
		for (DWORD i = 0; i < r_count; ++i)
		{
			if (!(ft->table[i].dwForwardDest))
			{
				delete [] bytes;
				return TRUE;
			}
		}
	}

	delete [] bytes;
	return FALSE;
}

int main()
{
	const char success[] = "Connection to Internet was successful!\n";
	const char fail[] = "Failed to connect to Internet!\n";
	DWORD written;

	HANDLE OutHandle = GetStdHandle(STD_OUTPUT_HANDLE);
	if (!OutHandle)
		exit(EXIT_FAILURE);

	if (InternetAvailable())
		WriteConsole(OutHandle, success, strlen(success), &written, NULL);
	else
		WriteConsole(OutHandle, fail, strlen(fail), &written, NULL);

        // Don't wanna include <iostream> just for a std::cin.get(). Use
        // system("PAUSE"), no harm ...
	system("PAUSE"); 
	return 0;
}


This post has been edited by sarmanu: 07 April 2010 - 12:18 PM

Was This Post Helpful? 1
  • +
  • -

#43 Anarion  Icon User is offline

  • The Persian Coder
  • member icon

Reputation: 282
  • View blog
  • Posts: 1,456
  • Joined: 16-May 09

Re: Week #14 Challenge: C++

Posted 07 April 2010 - 10:22 AM

View PostRaynes, on 07 April 2010 - 10:53 AM, said:

I'm using G++.

Then you might be using an old version. The newer ones work well :)
Was This Post Helpful? 0
  • +
  • -

#44 BetaWar  Icon User is offline

  • #include "soul.h"
  • member icon

Reputation: 1138
  • View blog
  • Posts: 7,110
  • Joined: 07-September 06

Re: Week #14 Challenge: C++

Posted 07 April 2010 - 12:34 PM

This is actually the first 52 weeks I have done, but I came up with something that I thought was very interesting and am actually planning on writing a tutorial on when I finish (is only about half way now, but it is enough that you can see what I am working on).

First off:
What it is
It is a home-grown compression algorithm (not the best out there) which I believe to be lossless (it is based partially off the huffman algorithm which is lossless).

In preliminary tests I was able to shorten the string "This is a test" to 5 characters (40 bits instead of 112) for a compression of over 64%. When I did this against a much larger file (plain text) (83.6 KB, the output file was a whole 6.25 KB, for a compression of over 92%!). Now, to give you a reference, when I zip the same input file the output file is 17 KB, only about 80% compression (granted zip files also store all the previous headers, which I am not doing). So I am quite pleased with it.

Anyways, here is the code (sorry it is a little choppy, I just started this yesterday):
#ifndef TREE_H
#define TREE_H

#include <iostream>
#include <string>

class Tree{
private:
	char c;
	Tree* l;
	Tree* r;
public:
	Tree(char character){
		c = character;
		l = r = NULL;
	}
	void insert(char input){
		if(isLeaf()){
			l = new Tree(c);
			r = new Tree(input);
		}
		else{
			r->insert(input);
		}
	}
	bool contains(char input) const{
		if(c == input){
			return true;
		}
		return r != NULL && r->contains(input);
	}
	bool is(char input) const{
		return isLeaf() && c == input;
	}
	bool isLeaf(void) const{
		return l == NULL && r == NULL;
	}
	void print(void) const{
		if(isLeaf()){
			std::cout << c << std::endl;
		}
		else{
			l->print();
			r->print();
		}
	}
	void pathTo(char character, std::string& str){
		if(isLeaf()){
			return;
		}
		if(!isLeaf() && l->is(character)){
			str += '0';
		}
		else{
			str += '1';
			r->pathTo(character, str);
		}
	}
};

class THold{
private:
	bool goLeft;
	Tree* l;
	Tree* r;
public:
	THold(void){
		goLeft = true;
		l = r = NULL;
	}
	~THold(void){
		delete l;
		delete r;
	}
	void insert(char c){
		if(goLeft && l == NULL){
			l = new Tree(c);
		}
		else if(goLeft){
			l->insert(c);
		}
		else if(!goLeft && r == NULL){
			r = new Tree(c);
		}
		else{
			r->insert(c);
		}
		goLeft = !goLeft;
	}
	bool contains(char c) const{
		return l->contains(c) || r->contains(c);
	}
	void print(void) const{
		l->print();
		r->print();
	}
	void pathTo(char c, std::string& str){
		if(l->contains(c)){
			str += '0';
			l->pathTo(c, str);
		}
		else if(r->contains(c)){
			str += '1';
			r->pathTo(c, str);
		}
	}
};

#endif


#ifndef COUNTER_H
#define COUNTER_H

class Counter{
private:
	char c;
	unsigned int count;
public:
	Counter(void){
		c = 0;
		count = 0;
	}
	Counter(char character){
		c = character;
		count = 0;
	}
	unsigned int getCount(void) const{
		return count;
	}
	char getChar(void) const{
		return c;
	}
	void operator++(int unused){
		count++;
	}
	Counter operator=(const Counter& source){
		c = source.getChar();
		count = source.getCount();
		return *this;
	}
};

#endif


#ifndef SORT_H
#define SORT_H

template<class dT, class rT> class Sort{ 
private: 
public: 
        Sort(void){ 
        } 
        ~Sort(void){ 
        } 
        void doSort(dT* array, int low, int high, rT(*sortFunction)(dT a, dT B)/>){ 
                int cLow = low; 
                int cHigh = high; 
                dT temp; 
                dT x = array[(low + high) / 2]; 
                do{ 
                        while (sortFunction(array[cLow], x) < 0){ 
                                cLow++; 
                        } 
                        while (sortFunction(array[cHigh], x) > 0){ 
                                cHigh--; 
                        } 
                        if (cLow <= cHigh){ 
                                temp = array[cLow];
                                array[cLow] = array[cHigh];
                                array[cHigh] = temp;
                                cLow++;
                                cHigh--;
                        } 
                } while (cLow <= cHigh); 
                if (low < cHigh){ 
                        doSort(array, low, cHigh, sortFunction); 
                } 
                if (cLow < high){ 
                        doSort(array, cLow, high, sortFunction); 
                } 
        } 
 
        static int sortAsc(dT a, dT B)/>{ 
                return a-b; 
        } 
        static int sortDesc(dT a, dT B)/>{ 
                return b-a; 
        } 
};

#endif


#include <iostream>
#include <string>

#include "Sort.h"
#include "Counter.h"
#include "Tree.h"

using namespace std;

int sortCounter(Counter a, Counter B)/>{
	return b.getCount()-a.getCount();
}

void initCounter(Counter chars[256]){
	for(int i = 0; i < 256; i++){
		chars[i] = Counter(i);
	}
}

unsigned int getInput(Counter chars[256], string& str, string& s){
	char input;
	unsigned int total = 0;
	while(!cin.eof()){
		input = cin.get();
		if(cin.eof()){
			break;
		}
		chars[input]++;
		total++;
		str += input;
	}
	return total;
}

void fillTree(THold& tree, Counter chars[256]){
	for(int i = 0;  i < 256 && chars[i].getCount() > 0; i++){
		tree.insert(chars[i].getChar());
	}
}

char* compressString(char* mem, unsigned int totalBytes, THold& tree, string& str){
	string paths = "";
	unsigned int bitsUsed = 0;
	unsigned int byteIndex = 0;
	char* finalMemory;
	double finalSize;
	for(unsigned int i = 0; i < str.length(); i++){
		tree.pathTo(str[i], paths);
	}
	for(unsigned int i = 0; i < paths.length(); i++){
		mem[byteIndex] += ((paths[i] == '1')?1:0);
		mem[byteIndex] *= 2;
		bitsUsed++;
		if(bitsUsed % 8 == 0){
			byteIndex++;
		}
	}

	finalMemory = (char*)malloc(byteIndex*sizeof(char));
	for(unsigned int i = 0; i < byteIndex+1; i++){
		finalMemory[i] = mem[i];
	}

	finalSize = 100*(1.0-((double)bitsUsed/(double)(totalBytes*8)));

//	cout << "Compressed by: " << finalSize << "%" << endl;

	return finalMemory;
}

string compress(string s = ""){
	// variables
	char* mem;
	char* finalMemory;
	Counter* chars = new Counter[256];
	Sort<Counter, int> sorter;
	THold tree;
	unsigned int totalBytes;
	string str = "";
	string final = "";

	// initiate the counter to all 0s
	initCounter(chars);
	// get the input, count the number of characters that were input, and calculate the max number of bytes needed after compression
	totalBytes = getInput(chars, str, s);
	// allocate the needed memory
	mem = (char*)calloc(totalBytes, sizeof(char));
	// sort the array based on number of characters
	sorter.doSort(chars, 0, 255, sortCounter);
	// fill the compression tree
	fillTree(tree, chars);
	// compress the string
	finalMemory = compressString(mem, totalBytes, tree, str);
	for(unsigned int i = 0; i < 256 && chars[i].getCount() > 0; i++){
		if(chars[i].getCount() > 0){
			final += chars[i].getChar();
		}
	}
	final += "\n\n";
	final += finalMemory;
	// clearn up and return
	delete mem;
	delete [] chars;
	return final;
}

int main(){
	string compressed = compress();
	cout << compressed << endl;
	return 0;
}


The sort algorithm I am using is actually one that I came up with a while ago (there is a tutorial on what it does and how it works in the C/C++ tutorials section if you are interested).

NOTE - Only tested on Windows 7 using Visual Studio 2008 express edition, though it should be cross platform as I didn't use anything othere than iostream and string.

Enjoy.
Was This Post Helpful? 1
  • +
  • -

#45 programble  Icon User is offline

  • (cons :dic :head)

Reputation: 49
  • View blog
  • Posts: 1,315
  • Joined: 21-February 09

Re: Week #14 Challenge: C++

Posted 07 April 2010 - 01:21 PM

View PostRaynes, on 07 April 2010 - 02:23 AM, said:

I'm using G++.


G++ seems to automagically include it:
$ cat test.cpp 
#include <iostream>

int main()
{
    std::string x = "";
    std::getline(std::cin, x);
    std::cout << x << std::endl;
    return 0;
}
$ g++ -v
Using built-in specs.
Target: i686-pc-linux-gnu
Configured with: ../configure --prefix=/usr --enable-shared --enable-languages=c,c++,fortran,objc,obj-c++,ada --enable-threads=posix --mandir=/usr/share/man --infodir=/usr/share/info --enable-__cxa_atexit --disable-multilib --libdir=/usr/lib --libexecdir=/usr/lib --enable-clocale=gnu --disable-libstdcxx-pch --with-tune=generic
Thread model: posix
gcc version 4.4.3 20100316 (prerelease) (GCC) 
$ g++ -o test test.cpp 
$ ./test
Hello
Hello
$ 


This post has been edited by programble: 07 April 2010 - 01:23 PM

Was This Post Helpful? 0
  • +
  • -

  • (5 Pages)
  • +
  • 1
  • 2
  • 3
  • 4
  • 5