10 Replies - 2291 Views - Last Post: 12 April 2012 - 07:35 AM Rate Topic: -----

#1 Swan7  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 7
  • Joined: 10-April 12

Problem with sorting my array using bubble sort

Posted 10 April 2012 - 10:57 PM

Hello all,

I've been working on a little word scrambler game for my class and I had the job of adding words and definitions from a external file and including a changable leaderboard from an external file. I had a structure holding score and a player's name. I would input the first ten scores form the leaderboard.txt and compare them to the 11th score (current player). However, it seems I cannot compare them to resave the top ten. I posted my code, everything works except in the switch(input) case(y or Y) if(strikes >= 3) section. I cannot exchange or compare values of the scoreArray[i].score.
Any solutions or pointers in the right direction for this issue would be really appreciated!


// Lab_10.cpp : Defines the entry point for the console application.
//

#include "stdafx.h"
#include <iostream>
#include <fstream>
#include <cstdlib>
#include <string>
#include <strstream>
#include <ctime>

using namespace std;

string scramble(string, int&, string&); //scrambles the word
int randomSelection(int); //random selection of a number to use in the array
const int maxLength = 200; 

struct word // words and the whole line of text from dictionary.txt
{	
	string line;
	string wrd;

};
struct leaderboard // yet to finish
{
	string line;
	string playerName;
	int score;
};

int _tmain(int argc, _TCHAR* argv[])
{
	int randNumb; // random integer
	word wordArray[maxLength];
	leaderboard scoreArray[11];
	string word1; // actual word
	string scrambled; // scrambled word
	string guess; // input to compare
	int vowels = 0;
	char input = 'Z';
	int test;
	scoreArray[10].score = 0;

	
		cout << "Welcome To WORD SCRAMBLER!" << endl;
		cout << "Would you like to play?" << endl;
		cout << "Enter [Y] to play or [N] to exit: ";
		cin >> input;

	ifstream infile; // streams in txt
	infile.open("dictionary.txt");
	if(infile.fail())
	{
		cout << "cannot find file"; // if the file should fail
		return -99;
	}

		while(!infile.eof())
	{
		for(int i = 0; i <= 50; i++) // gets fifty lines from file and saves it to the array
			{
				getline(infile, wordArray[i].line);
			}	
		
	}
		infile.close();

	for(int i = 0; i <= 40; i++) // seperates the word from the line
		{	
			int pos;
			pos = wordArray[i].line.find('|');
			string temp = wordArray[i].line.substr(0,pos);
			wordArray[i].wrd = temp;
		}	
		
	
	/*for(int i = 0; i <= 40; i++) This wouldve saved the definition to the wordArray[i].def but errors were occuring
		{	
			int pos;
			pos = wordArray[i].line.find('|');
			wordArray[i].def = wordArray[i].line.substr(pos+2, wordArray[i].line.length());
			
		}	*/
		
	
	while(input != 'n' && input != 'N')
	{ cout << "\n************************************New Round***********************************" << endl;
		scoreArray[10].score = 0;
		int strike = 0; // stub
		cout << "\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\nPress Enter to Continue!" << endl;
		cin.get();
		cin.get();
		
		

		while(input  != 'n' && input != 'N' && strike < 3)
{	
								
		scrambled.clear();
		randNumb = randomSelection(35);
		vowels = 0;
	        scramble(wordArray[randNumb].wrd, vowels, scrambled);

		cout << "\n\n\n\n\n\n\n\n\n\n";
																
		success = false; 
		int tries = 0;
								 

	while (success == false && tries < 5)
	{
									
	tries++;
	cout << "********************************************************************************" << endl;
	cout << "|			      Let's play WORD SCRAMBLER!                       |" << endl;;
	cout << "********************************************************************************" << endl;
	cout << "TRY NUMBER: " << tries << endl;
	cout << "\n\nNumber of vowels removed from word: " << vowels << endl;
	cout << "\nThe scrambled word is: " << scrambled << endl;
	int pos = wordArray[randNumb].line.find('|');
	string hint = wordArray[randNumb].line.substr(pos+2,wordArray[randNumb].line.length());
	//^ This saves the line without the word and "|" to a string
	cout << "\nDefinition: " << hint << endl;// hint is display
	cout << "\n\n\n\n\n";
	cout << "Please guess the word: ";
	cin >> guess;
	cout << "You guessed: " << guess << endl;


	if (guess.compare(wordArray[randNumb].wrd) == 0)
		 {
			 success = true;
		 }
	else
		 {
		     cout << "\nSorry, that is incorrect. Try again!" << endl << endl;

		 }
		}


		if (success == true)
		{
		  cout << "\n\nCongrats! You've guessed the word in " << tries << " attempts!";
		 scoreArray[10].score += 5 - (tries - 1);
	        cout << "\nThe word was: "<< wordArray[randNumb].wrd <<"\n\n\n\n\n\n\n\n\nCurrent Score: " << scoreArray[10].score;
		cout << "\n\n";
		}
		   else
		{
	cout << "\nSorry! You did not guess the word in 5 tries.  The word was: " << wordArray[randNumb].wrd;
	cout << "\n\n\n\n\n\n\n\nCurrent score: "<< scoreArray[10].score << "\n\n\n\n";
		strike++;
		}

							
		cout << "\nYou have " << strike << " strike(s).\n\n\n\n\n\n\n\n\n\n";
		cout << "\nWould you like to play again? ([y]es/[n]o)";
		cin >> input;
																	
		switch(input)
			{
			case 'Y':
			case 'y':
				if(strike >= 3)
		{
	{
										
cout << "\n\n\n\n\n\n\n\n\n\n\n\n\n*****************************************************************************" << endl;
cout << "You have chosen to play again.\nHowever, you have three strikes and must begin a new round!\n\nYou're score for this round was: " << scoreArray[10].score << endl;
cout << "\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\nPlease Enter Your Name for The Leaderboards: ";
cin >> scoreArray[10].playerName;
												
												
												
ifstream inLeaderBoard;
inLeaderBoard.open("Leaderboard.txt");
while(!inLeaderBoard.eof())
{
													
													
for(int i = 0; i < 10; i++)
	{	
inLeaderBoard >> scoreArray[i].score;
inLeaderBoard >> scoreArray[i].playerName;
														
														
	}
													inLeaderBoard.close();
														
													
	}

	for(int i = 0; i < 10; i++)
	{
	  scoreArray[i].score = (int)scoreArray[i].score;
	}
										
												
													


	bool ordered = false;
	int n = 0, k = 0,  y = 0, x = 0;
	while(ordered == false)
{
	for(int i = 0; i < 11; i++)
	{	
	if(scoreArray[i].score > scoreArray[i+1].score)
															x = scoreArray[i+1].score;
															y = scoreArray[i].score;
															scoreArray[i].score = x;
															scoreArray[i+1].score = y;
															
															
															
															k++;
	}
	if(k == 0)
	ordered == true;

	else 
															k = 0; 
	}	

													
														
												}	
												
													
													
														
	cout << "The score for this round was submitted for the leaderboards" << endl;
	cout << "Press enter to Continue\n";
	cin.get();
	cin.get();
	}

// TOOK OUT SOME CODE HERE TO KEEP THE POST SOMEWHAT SHORT

				EXIT_SUCCESS;

}


string scramble(string word1, int& vowels, string& scrambled)
{
for(int i = 0; i < word1.length(); i++)
switch(word1.at(i))
{
case 'A':
case 'a':
case 'e':
case 'E':
case 'I':
case 'i':
case 'O':
case 'o':
case 'U':
case 'u': vowels = vowels+1;
break;
default:
	if (bool x = rand() % 2)
	{
		scrambled = scrambled+word1.at(i);
	}
	else 
		{
			scrambled = word1.at(i)+scrambled;
		}


}



return scrambled;
}
int randomSelection(int num)
{
	int random;
	time_t t;
	time(&t);
	srand(t);

	random = rand() % 35;

	return random;

}




Is This A Good Question/Topic? 0
  • +

Replies To: Problem with sorting my array using bubble sort

#2 AmitTheInfinity  Icon User is offline

  • C Surfing ∞
  • member icon

Reputation: 119
  • View blog
  • Posts: 1,565
  • Joined: 25-January 07

Re: Problem with sorting my array using bubble sort

Posted 10 April 2012 - 11:54 PM

Please don't double post. It's not going to help you to get answers faster.
Was This Post Helpful? 0
  • +
  • -

#3 Swan7  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 7
  • Joined: 10-April 12

Re: Problem with sorting my array using bubble sort

Posted 11 April 2012 - 12:07 AM

View PostAmitTheInfinity, on 10 April 2012 - 11:54 PM, said:

Please don't double post. It's not going to help you to get answers faster.


Sorry, I'm new to this forum and didn't intend to double post. Not quite sure how that happened . I'll delete the other post.
Was This Post Helpful? 0
  • +
  • -

#4 r.stiltskin  Icon User is offline

  • D.I.C Lover
  • member icon

Reputation: 1833
  • View blog
  • Posts: 4,927
  • Joined: 27-December 05

Re: Problem with sorting my array using bubble sort

Posted 11 April 2012 - 10:20 AM

In this section of your code
while(!inLeaderBoard.eof())
{
    for(int i = 0; i < 10; i++)
    {	
        inLeaderBoard >> scoreArray[i].score;
        inLeaderBoard >> scoreArray[i].playerName;
    }
    inLeaderBoard.close();
}


the outer while loop serves no purpose. It tests for eof first (when it can't be at eof since you just opened the file), then the inner for loop reads 10 records and closes the file (which is still not at eof if the file contains 10 records). Then you enter the while loop again, and try to read 10 more numbers from the already-closed file. At this point, maybe it turns the eof flag on. I'm not sure whether that is guaranteed since you're trying to read from a closed stream. It might just end up as an infinite loop. But in any case, it makes no sense.

Then the next section says
for(int i = 0; i < 10; i++)
{
    scoreArray[i].score = (int)scoreArray[i].score;
}


copying the array to itself? Surely that's not what you meant.

****************************************************************

Your code as posted can't be compiled. And your project is not correctly configured as a console application. And for such a small program there's no reason to use precompiled headers.

Here are instructions for setting up a console application correctly in Visual C++:
Setting up a project in Visual C++ for ordinary C++ programs (i.e., not Windows GUI applications):

Open the New Project window, select Win32 Console Application, type a project name & click OK

That opens the Application Wizard window. DON'T click Finish. Instead, click Next.

On the next window, under "Additional options", click Empty project. Now click Finish.

You now have a new, empty "console solution" ready to go.

****************************************

Adding files to the project:

Next, the Solution Explorer should appear (usually in a panel on the left side of your screen). If you don't see it, click View, then click Solution Explorer.

To add a new file to your project (this applies to your initial program .cpp file as well as any additional header and source files you want to add to the project), in the Solution Explorer right-click on Source Files. Point your cursor to Add, then click on New Item, then select the type of file you want to add (for beginners this will usually be a C++ File or a Header file), then near the bottom of the panel enter a name for the file, and finally click Add.

(If you want to add an already-existing file to a project, you can click on Existing Item and use the explorer window that opens to locate and select your file. However, the file should already be located in an appropriate folder for the project. Therefore this method isn't recommended for beginners unless you fully-understand the appropriate directory structure for Visual Studio projects. It's safer to let Visual Studio add a new empty file and then copy and paste your existing code into that new file.)

You can also add a file to the project by clicking Project on the Toolbar at the top of the window, then click Add New Item and then proceed as described above.


You now have an empty file in which to write your program. When ready to test your program, build it by pressing F7, then run it by typing Ctrl-F5 (that means press and hold the Control key while you press the F5 key) and the terminal window will stay open when the program finis
Was This Post Helpful? 1
  • +
  • -

#5 Swan7  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 7
  • Joined: 10-April 12

Re: Problem with sorting my array using bubble sort

Posted 11 April 2012 - 02:11 PM

r.stiltskin

Thanks a lot for looking through my code. I created a new project and made it an empty project and copy and pasted my code. Also I fixed the useless loops I included. In my project with the precompiled headers I was able to run my code and actually swap the integer values of the array scoreArray.[].score. However, I still cannot swap the string values in scoreArray.playerName. In addition, I cannot run my code in the empty project that you suggested. I'm guessing I did something wrong setting up the project =\. I posted the source code for the empty project. If you could explain what I did wrong setting up the new project as well as why I cannot swap string values, I'd appreciate it!

Thanks!!

code

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

using namespace std;

string scramble(string, int&, string&); //scrambles the word
int randomSelection(int); //random selection of a number to use in the array
const int maxLength = 200; 

struct word // words and the whole line of text from dictionary.txt
{	
	string line;
	string wrd;

};
struct leaderboard // yet to finish
{
	
	char playerName[25];
	int score;
};

int main()
{
	int randNumb; // random integer
	word wordArray[maxLength];
	leaderboard scoreArray[11];
	string word1; // actual word
	string scrambled; // scrambled word
	string guess; // input to compare
	int vowels = 0;
	char input = 'Z';
	int test;
	scoreArray[10].score = 0;

	
		cout << "Welcome To WORD SCRAMBLER!" << endl;
		cout << "Would you like to play?" << endl;
		cout << "Enter [Y] to play or [N] to exit: ";
		cin >> input;

	ifstream infile; // streams in txt
	infile.open("dictionary.txt");
	if(infile.fail())
	{
		cout << "cannot find file"; // if the file should fail
		return -99;
	}

		while(!infile.eof())
	{
		for(int i = 0; i <= 50; i++) // gets fifty lines from file and saves it to the array
			{
				getline(infile, wordArray[i].line);
			}	
		
	}
		infile.close();

	for(int i = 0; i <= 40; i++) // seperates the word from the line
		{	
			int pos;
			pos = wordArray[i].line.find('|');
			string temp = wordArray[i].line.substr(0,pos);
			wordArray[i].wrd = temp;
		}	
		
	
	/*for(int i = 0; i <= 40; i++) This wouldve saved the definition to the wordArray[i].def but errors were occuring
		{	
			int pos;
			pos = wordArray[i].line.find('|');
			wordArray[i].def = wordArray[i].line.substr(pos+2, wordArray[i].line.length());
			
		}	*/
		
	
	while(input != 'n' && input != 'N')
	{ cout << "\n************************************New Round***********************************" << endl;
		scoreArray[10].score = 0;
		int strike = 0; // stub
		cout << "\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\nPress Enter to Continue!" << endl;
		cin.get();
		cin.get();
		
		

						while(input  != 'n' && input != 'N' && strike < 3)
							{	
								
								scrambled.clear();
								randNumb = randomSelection(35);
								vowels = 0;
								scramble(wordArray[randNumb].wrd, vowels, scrambled);

								cout << "\n\n\n\n\n\n\n\n\n\n";
								/*cout << "\n\nNumber of vowels removed from word: " << vowels << endl;
								cout << "The scrambled word is: " << scrambled << endl;
								int pos = wordArray[randNumb].line.find('|');
								string hint = wordArray[randNumb].line.substr(pos+2,wordArray[randNumb].line.length());
								//^ This saves the line without the word and "|" to a string
								cout << "Definition: " << hint << endl;// hint is display
								cout << "\n\n\n\n\n\n\n\n\n\n\n\n\n\n";*/
								
								bool success = false; 
								int tries = 0;
								 // stub


							while (success == false && tries < 5)
								{
									
									tries++;
									cout << "********************************************************************************" << endl;
									cout << "|			      Let's play WORD SCRAMBLER!                       |" << endl;;
									cout << "********************************************************************************" << endl;
									cout << "TRY NUMBER: " << tries << endl;
									cout << "\n\nNumber of vowels removed from word: " << vowels << endl;
									cout << "\nThe scrambled word is: " << scrambled << endl;
									int pos = wordArray[randNumb].line.find('|');
									string hint = wordArray[randNumb].line.substr(pos+2,wordArray[randNumb].line.length());
									//^ This saves the line without the word and "|" to a string
									cout << "\nDefinition: " << hint << endl;// hint is display
									cout << "\n\n\n\n\n";
										
										cout << "Please guess the word: ";
										cin >> guess;
										cout << "You guessed: " << guess << endl;


										if (guess.compare(wordArray[randNumb].wrd) == 0)
											 {
													 success = true;
											 }
										else
											 {
													  cout << "\nSorry, that is incorrect. Try again!" << endl << endl;

											 }
								}


								if (success == true)
									{
									   cout << "\n\nCongrats! You've guessed the word in " << tries << " attempts!";
									   scoreArray[10].score += 5 - (tries - 1);
									   test =  scoreArray[10].score;
									    cout << "\nThe word was: "<< wordArray[randNumb].wrd <<"\n\n\n\n\n\n\n\n\nCurrent Score: " << scoreArray[10].score;
										cout << "\n\n";
									}
								else
									{
										cout << "\nSorry! You did not guess the word in 5 tries.  The word was: " << wordArray[randNumb].wrd;
										cout << "\n\n\n\n\n\n\n\nCurrent score: "<< scoreArray[10].score << "\n\n\n\n";
										strike++;
										 
									}

							
										cout << "\nYou have " << strike << " strike(s).\n\n\n\n\n\n\n\n\n\n";
										cout << "\nWould you like to play again? ([y]es/[n]o)";
								
										cin >> input;
								// Haven't developed code for to quit game if you have three strikes
									
									switch(input)
									{
										case 'Y':
										case 'y':
												if(strike >= 3)
												{
												
										
												cout << "\n\n\n\n\n\n\n\n\n\n\n\n\n*****************************************************************************" << endl;
												cout << "You have chosen to play again.\nHowever, you have three strikes and must begin a new round!\n\nYou're score for this round was: " << scoreArray[10].score << endl;
												cout << "\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\nPlease Enter Your Name for The Leaderboards: ";
												cin >> scoreArray[10].playerName;
												
												
												
												ifstream inLeaderBoard;
												inLeaderBoard.open("Leaderboard.txt");
												
													
													for(int i = 0; i < 10; i++)
													{	
														inLeaderBoard >> scoreArray[i].score;
														inLeaderBoard >> scoreArray[i].playerName;
													}
													inLeaderBoard.close();
														
													
												

													for(int i = 0; i < 11; i++)
														{
															cout << "" << scoreArray[i].score << " " << "" << scoreArray[i].playerName << endl;
														}
										
													

													
													int swapHolder = -1;
													char nameSwapHolder[25];
													int end = 11;
													int length = 11;
													for(int counter = length-1; counter >= 0; counter--)
														for(int i = 0; i < end; i++)
														{	
															if(scoreArray[i].score < scoreArray[i+1].score) // This is a bubble sort method for comparing values. I tried swapping //string values using the same method in this loop but i kept getting errors
															{	
																	swapHolder = scoreArray[i+1].score;
																	scoreArray[i+1].score = scoreArray[i].score;
																	scoreArray[i].score = swapHolder;
															}
															
														}
														
													end--;
												
													for(int i = 0; i < 11; i++)
														{
															cout << "" << scoreArray[i].score << " " << "" << scoreArray[i].playerName << endl;
														}

													
														
												
												
													
													
														
												cout << "The score for this round was submitted for the leaderboards" << endl;
												cout << "Press enter to Continue\n";
												cin.get();
												cin.get();
									}
										break;
										case 'n':
										case 'N':
											{cout << "\n\n\n\n\n\n\n\n\n\n\n\n\n*****************************************************************************" << endl;
											cout << "You have chosen to quit.\nYou're score for this round was: " << scoreArray[10].score << endl;
												cout << "\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\nPlease Enter Your Name for The Leaderboards: ";
												cin >> scoreArray[10].playerName;
												
												ifstream inLeaderBoard;
												inLeaderBoard.open("Leaderboard.txt");		
													
													for(int i = 0; i < 10; i++)
													{	
														inLeaderBoard >> scoreArray[i].score;
														inLeaderBoard >> scoreArray[i].playerName;
													}
													inLeaderBoard.close();
												

													
												
													
												cin.get();
											}
												break;
										default: 
											{cout << "Invalid entry. Please enter Y or N to continue." << endl;
												break;}


									
	}
				
	}
}
		cin.get();
			

		EXIT_SUCCESS;

}


string scramble(string word1, int& vowels, string& scrambled)
{
for(int i = 0; i < word1.length(); i++)
switch(word1.at(i))
{
case 'A':
case 'a':
case 'e':
case 'E':
case 'I':
case 'i':
case 'O':
case 'o':
case 'U':
case 'u': vowels = vowels+1;
break;
default:
	if (bool x = rand() % 2)
	{
		scrambled = scrambled+word1.at(i);
	}
	else 
		{
			scrambled = word1.at(i)+scrambled;
		}


}



return scrambled;
}
int randomSelection(int num)
{
	int random;
	time_t t;
	time(&t);
	srand(t);

	random = rand() % 35;

	return random;
}


Was This Post Helpful? 0
  • +
  • -

#6 r.stiltskin  Icon User is offline

  • D.I.C Lover
  • member icon

Reputation: 1833
  • View blog
  • Posts: 4,927
  • Joined: 27-December 05

Re: Problem with sorting my array using bubble sort

Posted 11 April 2012 - 02:39 PM

Delete line 5.
Actually ,the correct name of the header that includes the std::stringstream class is <sstream>, not <strstream> (strstream is deprecated), but you don't seem to be using stringstreams so why include the header?

(Which version of Visual C++ are you using?)

I'm able to compile the program with no errors, but my compiler gives the following warnings which you should investigate (each one has a line number that refers to the specific line of the program that produced it):
test.cc: In function ‘int main()’:
test.cc:208: warning: unused variable ‘nameSwapHolder’
test.cc:280: warning: statement has no effect
test.cc: In function ‘std::string scramble(std::string, int&, std::string&)’:
test.cc:287: warning: comparison between signed and unsigned integer expressions
test.cc:302: warning: unused variable ‘x’
test.cc: At global scope:
test.cc:318: warning: unused parameter ‘num’

Aside from that, it's not clear exactly what problems you're asking about. You'll have to provide more details, such as what input you're giving the program, what output you expected and what output you got instead.

What does that mean, you "can't run the code in the empty project"? Did you explicitly ADD your source file to the project? Did you put a copy of your input data file "dictionary.txt" in the new project directory? Can you build the program? Is there an error message? Give details.

This post has been edited by r.stiltskin: 11 April 2012 - 02:47 PM
Reason for edit:: adjusted line numbers to correspond to code in Post #5

Was This Post Helpful? 1
  • +
  • -

#7 Swan7  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 7
  • Joined: 10-April 12

Re: Problem with sorting my array using bubble sort

Posted 11 April 2012 - 07:34 PM

Okay so I kind of realized I'm being very vague and somewhat wasting your time with code that has no affect on the program. I'm going to break this down in a clearer way with updated code.

The program now runs since I added dictionary.txt as well as the leaderboard.txt to the file.
The program functions fine displaying words from dictionary.txt to guess.
If the user gets three strikes he is prompted to enter a name for his score before beginning a new round.
At this point I import the scores and names from the leaderboard.txt.
The output of the array looks like this and is correct:
8 Austen
2 Cait
10 Ty
7 Chal
6 Ant
5 Mark
1 Joe
3 Karl
9 Rob
4 Ryan

I displayed the array to the tenth position and it is identical with the addition of the current score and player at the end.
When using the bubble method stated in case y and Y, I can swap the values of scoreArray[i].score and scoreArray[i+1].score.
The issue: I'm having is I cannot swap the contents of scoreArray[i].playerName and scoreArray[i+1].playerName. I keep getting errors. If I remove the string swapping portion of the bubble sort and only run the scores portion, the scores will swap from greatest to least and the names remain in the same position. In addition, the first time in the loop calculating the leaderboard I get a strange value for the current score but the second time it fixes.

Note case n and N will be identical to the contents of case y and Y once its running properly.

if the current players name is "John" and his score is "5"
first loop
157 Austen
10 Cait
9 Ty
8 Chal
7 Ant
6 Mark
5 Joe
5 Karl
4 Rob
3 Ryan
2 John
second loop
10 Austen
9 Cait
8 Ty
7 Chal
6 Ant
5 Mark
5 Joe
4 Karl
3 Rob
2 Ryan
1 John

So ultimately, I am trying to be able to swap strings so the name follows the score. And of course fix the strange value when calculating the order in the first loop. I hope this helps clear things up.

Thanks so much for your time rumple stiltskin!


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

using namespace std;

string scramble(string, int&, string&); //scrambles the word
int randomSelection(int); //random selection of a number to use in the array
const int maxLength = 200; 

struct word // words and the whole line of text from dictionary.txt
{	
	string line;
	string wrd;

};
struct leaderboard // yet to finish
{
	
	string playerName;
	int score;
};

int main()
{
	int randNumb; // random integer to select a word
	word wordArray[maxLength];
	leaderboard scoreArray[11];
	string word1; // actual word
	string scrambled; // scrambled word
	string guess; // input to compare
	int vowels = 0;
	char input = 'Z';
	scoreArray[10].score = 0;

	
		cout << "Welcome To WORD SCRAMBLER!" << endl;
		cout << "Would you like to play?" << endl;
		cout << "Enter [Y] to play or [N] to exit: ";
		cin >> input;

	ifstream infile; // streams in txt
	infile.open("dictionary.txt");
	if(infile.fail())
	{
		cout << "cannot find file"; // if the file should fail
		return -99;
	}

		while(!infile.eof())
	{
		for(int i = 0; i <= 50; i++) // gets fifty lines from file and saves it to the array
			{
				getline(infile, wordArray[i].line);
			}	
		
	}
		infile.close();

	for(int i = 0; i <= 40; i++) // seperates the word from the line
		{	
			int pos;
			pos = wordArray[i].line.find('|');
			string temp = wordArray[i].line.substr(0,pos);
			wordArray[i].wrd = temp;
		}	
		
	
	/*for(int i = 0; i <= 40; i++) This wouldve saved the definition to the wordArray[i].def but errors were occuring
		{	
			int pos;
			pos = wordArray[i].line.find('|');
			wordArray[i].def = wordArray[i].line.substr(pos+2, wordArray[i].line.length());
			

		}	*/
		
	
	while(input != 'n' && input != 'N')
	{ cout << "\n************************************New Round***********************************" << endl;
		scoreArray[10].score = 0;
		int strike = 0; // stub
		cout << "\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\nPress Enter to Continue!" << endl;
		cin.get();
		cin.get();
		
		

			while(input  != 'n' && input != 'N' && strike < 3)
				{	
							
					scrambled.clear();
					randNumb = randomSelection(35);
					vowels = 0;
					scramble(wordArray[randNumb].wrd, vowels, scrambled);

					cout << "\n\n\n\n\n\n\n\n\n\n";
				

					bool success = false; 
					int tries = 0;
					 // stub


			while (success == false && tries < 5)
			{
									
			tries++;
		cout << "********************************************************************************" << endl;
		cout << "|			      Let's play WORD SCRAMBLER!                       |" << endl;
		cout << "********************************************************************************" << endl;
		cout << "TRY NUMBER: " << tries << endl;
		cout << "\n\nNumber of vowels removed from word: " << vowels << endl;
		cout << "\nThe scrambled word is: " << scrambled << endl;
		int pos = wordArray[randNumb].line.find('|');
		string hint = wordArray[randNumb].line.substr(pos+2,wordArray[randNumb].line.length());
		//^ This saves the line without the word and "|" to a string
		cout << "\nDefinition: " << hint << endl;// hint is display
		cout << "\n\n\n\n\n";
																	cout << "Please guess the word: ";
		cin >> guess;
		cout << "You guessed: " << guess << endl;


		if (guess.compare(wordArray[randNumb].wrd) == 0)
			 {
				 success = true;
			 }
		else
			 {
				  cout << "\nSorry, that is incorrect. Try again!" << endl << endl;

			 }
		}


			if (success == true)
				{
			  cout << "\n\nCongrats! You've guessed the word in " << tries << " attempts!";
			  scoreArray[10].score += 5 - (tries - 1);
                          cout << "\nThe word was: "<< wordArray[randNumb].wrd <<"\n\n\n\n\n\n\n\n\nCurrent Score: " << scoreArray[10].score;
			  cout << "\n\n";
				}
				  else
				{
				cout << "\nSorry! You did not guess the word in 5 tries.  The word was: " << wordArray[randNumb].wrd;
				cout << "\n\n\n\n\n\n\n\nCurrent score: "<< scoreArray[10].score << "\n\n\n\n";
				strike++;						 
				}

							
			cout << "\nYou have " << strike << " strike(s).\n\n\n\n\n\n\n\n\n\n";
			cout << "\nWould you like to play again? ([y]es/[n]o)";
								
			cin >> input;
			// Haven't developed code for to quit game if you have three strikes
									
			switch(input)
			{
				case 'Y':
				case 'y':
					if(strike >= 3)
					{
					cout << "\n\n\n\n\n\n\n\n\n\n\n\n\n*****************************************************************************" << endl;
					cout << "You have chosen to play again.\nHowever, you have three strikes and must begin a new round!\n\nYou're score for this round was: " << scoreArray[10].score << endl;
					cout << "\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\nPlease Enter Your Name for The Leaderboards: ";
					cin >> scoreArray[10].playerName;
												
												
												
			         ifstreaminLeaderBoard;				
                                 inLeaderBoard.open("Leaderboard.txt");
												
													
				for(int i = 0; i < 10; i++)
				{	
					inLeaderBoard >> scoreArray[i].score;
					inLeaderBoard >> scoreArray[i].playerName;
				}
												
                                inLeaderBoard.close();
														
													
												

				for(int i = 0; i < 11; i++) //tests if the information retrieved is correct
				{
				cout << "" << scoreArray[i].score << " " << "" << scoreArray[i].playerName << endl;
				}
										
													

													
				int swapHolder = -1;
				string temp;
				int length = 11;
				int end = 11;

				for(int counter = length-1; counter >= 0; counter--)
					for(int i = 0; i < end; i++)
					{	
				if(scoreArray[i].score < scoreArray[i+1].score) 
 

					   {	
						swapHolder = scoreArray[i+1].score;
						scoreArray[i+1].score = scoreArray[i].score;
						scoreArray[i].score = swapHolder;
						temp = scoreArray[i+1].playerName;
						scoreArray[i+1].playerName = scoreArray[i].playerName;
						scoreArray[i].playerName = temp;

                             // This is a bubble sort method for comparing values. I tried swapping 
                             //string values using the same method in this loop but i kept getting errors
                             //if i take out the portion for playerName swap it runs the scores fine
					    }
															
					}
														
					end--;
												
			for(int i = 0; i < 11; i++) // compares to the test
			cout << "" << scoreArray[i].score << " " << "" << scoreArray[i].playerName << endl;
														

													
														
												
												
													
													
														
			cout << "The score for this round was submitted for the leaderboards" << endl;
			cout << "Press enter to Continue\n";
			cin.get();
			cin.get();
		}
		break;
		   case 'n':
		   case 'N':
			{cout << "\n\n\n\n\n\n\n\n\n\n\n\n\n*****************************************************************************" << endl;
			 cout << "You have chosen to quit.\nYou're score for this round was: " << scoreArray[10].score << endl;
			 cout << "\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\nPlease Enter Your Name for The Leaderboards: ";
			 cin >> scoreArray[10].playerName;
												
			ifstream inLeaderBoard;
                        inLeaderBoard.open("Leaderboard.txt");		
													
			for(int i = 0; i < 10; i++)
				{	
				inLeaderBoard >> scoreArray[i].score;
				inLeaderBoard >> scoreArray[i].playerName;
				}
			inLeaderBoard.close();
												

													
			cin.get();
		}
		break;
			default: 
			{cout << "Invalid entry. Please enter Y or N to continue." << endl;
			break;}


									
	}
				
	}
}
		cin.get();
			

		EXIT_SUCCESS;

}


string scramble(string word1, int& vowels, string& scrambled)
{
for(int i = 0; i < word1.length(); i++)
switch(word1.at(i))
{
case 'A':
case 'a':
case 'e':
case 'E':
case 'I':
case 'i':
case 'O':
case 'o':
case 'U':
case 'u': vowels = vowels+1;
break;
default:
	if (bool x = rand() % 2)
	{
		scrambled = scrambled+word1.at(i);
	}
	else 
		{
			scrambled = word1.at(i)+scrambled;
		}


}



return scrambled;
}
int randomSelection(int num)
{
	int random;
	time_t t;
	time(&t);
	srand(t);

	random = rand() % 35;

	return random;
}


Was This Post Helpful? 0
  • +
  • -

#8 Swan7  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 7
  • Joined: 10-April 12

Re: Problem with sorting my array using bubble sort

Posted 11 April 2012 - 07:47 PM

Oh and I'm using Visual Studio 2010.
Was This Post Helpful? 0
  • +
  • -

#9 r.stiltskin  Icon User is offline

  • D.I.C Lover
  • member icon

Reputation: 1833
  • View blog
  • Posts: 4,927
  • Joined: 27-December 05

Re: Problem with sorting my array using bubble sort

Posted 11 April 2012 - 08:54 PM

In your bubblesort, your entire scoreArray has 11 elements and you have set end to 11, so your loop counter i takes every value from 0 to 10, and compares scoreArray[i] to scoreArray[i+1]. That means that when i == 10 you're comparing the value of scoreArray[10] (the last element in the array) to scoreArray[11]. See a problem there?

Presumably that's where you're getting random strange values. Actually, when you do that the program could crash, since you're accessing memory that doesn't belong to the array, and might not belong to this program.

Aside from that, you're doing too much work and not taking advantage of your struct leaderboard which is a datatype itself. There's no need to swap the scores and the names separately. You can swap a complete leaderboard object as a single unit. Just declare your swapHolder to be a leaderboard instead of an int.
Was This Post Helpful? 1
  • +
  • -

#10 Swan7  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 7
  • Joined: 10-April 12

Re: Problem with sorting my array using bubble sort

Posted 12 April 2012 - 06:23 AM

Yeah, cause the eleventh element of the array is actually saved at [10] rather than [11]. How did I not catch that? >.<

Also, thanks for the knowledge on the utilizing a complete struct object as a unit. Really does cut down the headache/code.

Alas my problem is resolved!

Thank you very much r.stilskin for your time and patience! You rock!
Was This Post Helpful? 0
  • +
  • -

#11 r.stiltskin  Icon User is offline

  • D.I.C Lover
  • member icon

Reputation: 1833
  • View blog
  • Posts: 4,927
  • Joined: 27-December 05

Re: Problem with sorting my array using bubble sort

Posted 12 April 2012 - 07:35 AM

Good.

I didn't want to confuse matters with this yesterday, but there are two easy optimizations that you should incorporate into your bubble sort. As it stands now, for an array of size n you scan the entire array n times, meaning that whatever you sort you perform exactly n2 comparisons (plus an unknown number of swaps). This means that even if the array is completely sorted before you start, you'll still perform at least n2 operations.

So first you can add the ability to recognize when the array is sorted and avoid unnecessary processing. You can declare a variable swapped of bool datatype (can only have values true or false) before the sorting and set it to false as the first step inside the outer loop. And inside the swapping section, whenever two elements are swapped set swapped to true. Now, when you reach the end of each full scan of the array, if the value of swapped is still false it will indicate that every element was larger (or smaller, in an ascending sort) than the next element -- in other words the array is completely sorted. So, after the end of the inner loop, you can add if(swapped == false) break; as the last line of the outer loop to break out of the loop and discontinue sorting.

The other easy optimization is to recognize that at the end of a full pass through the array, the very smallest (or largest in an ascending sort) element is in the last position of the array. There's no need to look at that one ever again. So "shorten" the array. In other words, on the next pass, don't bother comparing array[n-2] to array[n-1] because you already know that array[n-1] is in its correct position. And on the pass after that, you can skip comparing array[n-3] to array[n-2]. And so on. So each time you increment i, you can decrement end.

And finally, if you use the swapped variable to determine when the sorting is finished, there's no need to count iterations of the outer loop, so you can replace that outer for loop with simply while (true), in other words an infinite loop.

This post has been edited by r.stiltskin: 12 April 2012 - 08:47 AM

Was This Post Helpful? 0
  • +
  • -

Page 1 of 1