I'm having a little bit problem with my game. What I want is when one out of two arrays becomes all 0's the loop will stop. Currently the loop stops when both arrays are equal to zero.
What I think is the problem but don't have a solution is that I have both array statements in one loop, it will run from top too bottom EVEN if array1(border1) has gotten all 0's.
What to you think?
void ShootAtShip(int board1[], int board2[], string names[], int cap) {
const int hit = 0;
int shot = 0;
bool won = false;
int temp;
for (int i = 0; i < cap; i++) {
while ((board1[i] != 0 || board2[i] != 0)) { //detects if any board has all their ships shot down
cout << names[1] << " set a position to shoot." << endl;
cin >> shot;
temp = shot;
while ((shot >= cap) || (shot < 0)) { //detects if the number is allowed
cout << "That number is not allowed, "<< names[1] << " set a position to shoot." << endl;
cin >> shot;
}
if (board1[shot] != 0) {
board1[shot] = 0;
cout << "Hit!" << endl;
}
else {
cout << "You missed." << endl;
}
shot = 0;
cout << names[0] << " set a position to shoot." << endl;
cin >> shot;
while ((shot >= cap) || (shot < 0)) { //detects if the number is allowed
cout << "That number is not allowed, " << names[0] << " set a position to shoot." << endl;
cin >> shot;
}
if (board2[shot] != 0) {
board2[shot] = 0;
cout << "Hit!" << endl;
}
else {
cout << "You missed." << endl;
}
}
}
cout << "Testing is while loop stops";
}
The key is that you have to check the state of the entire board at each loop iteration. Like this:
void ShootAtShip(int board1[], int board2[], string names[], int cap) {
for (int i = 0; i < cap; i++)
{
while ( 1 )
{
bool board1HasShips = false;
bool board2HasShips = false;
for ( int j = 0; j < cap; j++ )
{
if ( board1[j] != 0 )
{
board1HasShips = true;
break;
}
}
for ( int j = 0; j < cap; j++ )
{
if ( board2[j] != 0 )
{
board2HasShips = true;
break;
}
}
if ( !board1HasShips || !board2HasShips ) break;
// past this point we know that both boards have ships.
// shoot at ships
}
}
}
Especially when writing games, it's a good idea to try and organize your code into functions.
Personally I would do something like this:
bool isGameOver(int board1[], int board2[], size_t cap)
{
bool lost1 = true;
bool lost2 = true;
for (size_t i = 0; i < cap && lost1 != false; ++i)
if (board1[i] != 0)
lost1 = false;
if (lost1)
return true;
for (size_t i = 0; i < cap && lost2 != false; ++i)
if (board2[i] != 0)
lost2 = false;
return lost2;
}
Then use this as a conditional to break the loop.
Since you are using c++ however, why not abstract the boards into a class? This would allow you to store info such as how many ships are left in each board.
Also consider using the std::array class template in c++ so you won't have to pass the array size seperately and try to use size_t or std::size_t for array indexing.
Related
School assignment for coding a cows and bulls game. Final scoring loops not working and I am not sure what the reason is.
I have tried renaming the vectors, changing iterators, changing where in the code the vectors are declared/initialized (still not sure exactly the difference)
//Get Number to Guess
if (numlen == 0) {
cout << "Enter the number to guess: ";
cin >> num;
cout << "Enter the number of digits in code: ";
cin >> numlen;
numstr = to_string(num);
if (numstr.length() < numlen) {
int diff = numlen - numstr.length();
addz = (diff, "0");
for (int z = 1; z <= diff; ++z) {
numstr = addz + numstr;
}
num = stoi(numstr);
}
vector<int> numvct(numlen, 0);
max1 = 1;
for (l = 1; l < numlen; ++l) {
max1 = max1 * 10;
}
for (j = max1, k = 0; j >= 1, k < numlen; j = j / 10, ++k) {
int addval1 = num / j;
num = num - (addval1 * j);
numvct.at(k) = addval1;
}
cout << "Number to guess: ";
for (r = 0; r < numlen; ++r) {
if (r == (numlen - 1)) {
cout << numvct.at(r) << endl;
}
else {
cout << numvct.at(r) << "-";
}
}
}
else {
//Fill vector to pick from
for (i = 0; i <= 9; ++i) {
pickvct.push_back(i);
}
//Pull to random number
vector<int> numvct(numlen);
for (k = 0; k < numlen; ++k) {
tempnum1 = rand() % (pickvct.size() - 1);
numvct.at(k) = pickvct.at(tempnum1);
pickvct.erase(pickvct.begin() + tempnum1);
}
cout << "Number to guess: ";
for (r = 0; r < numlen; ++r) {
if (r == (numlen - 1)) {
cout << numvct.at(r) << endl;
}
else {
cout << r << "-";
}
}
}
//Get guess
do {
do {
cout << "Enter guess: ";
cin >> guess;
guessstr = to_string(guess);
guesslen = guessstr.length();
if (guesslen < numlen) {
int diff = numlen - guesslen;
addz = (diff, "0");
for (int z = 1; z <= diff; ++z) {
guessstr = addz + guessstr;
}
guess = stoi(guessstr);
guesssame = true;
}
if (guesslen == numlen) {
guesssame = false;
}
while (guesslen > numlen) {
cout << "You can only enter " << numlen << " digits." << endl;
cout << "Enter guess: ";
cin >> guess;
guessstr = to_string(guess);
guesslen = guessstr.length();
}
for (s = 0; s < guesslen; ++s) {
for (t = s + 1; t < guesslen; ++t) {
if (guessstr.at(s) == guessstr.at(t)) {
guesssame = true;
}
else {
guesssame = false;
}
}
}
if (guesssame == true) {
cout << "Each number must be different." << endl;
guesssame = true;
}
} while (guesssame == true);
vector<int> guessvct(guesslen, 0);
max2 = 1;
for (m = 1; m < guesslen; ++m) {
max2 = max2 * 10;
}
for (n = max2, o = 0; n >= 1, o < guesslen; n = n / 10, ++o) {
addval2 = guess / n;
guess = guess - (addval2 * n);
guessvct.at(o) = addval2;
}
//Check the guess
for (p = 0; p < guesslen; ++p) {
guessdigit = guessvct.at(p);
cout << "Guess digit at " << p << ": " << guessdigit << endl;
for (q = 0; q < guesslen; ++q) {
numdigit = numvct.at(q);
cout << "Num digit at " << q << ": " << numdigit << endl;
if (numdigit == guessdigit && q == p) {
bulls = bulls + 1;
if (bulls == numlen) {
win = true;
break;
}
cout << bulls << " bulls" << endl;
}
else {
if (numdigit == guessdigit && q != p) {
cows = cows + 1;
cout << cows << " cows" << endl;
}
}
}
}
} while (win == false);
To make sure the loop was working right I added the cout statements but it is printing the first one only:
Enter guess: ####
Guess digit at 0: #
Program finished
//Get Number to Guess
if (numlen == 0) {
...
}
else {
//Fill vector to pick from
...
}
Within this if else block, you have the following two lines:
vector<int> numvct(numlen, 0);
and
vector<int> numvct(numlen);
These lines declare and initialize vectors which pass out of scope when the program leaves their respective if / else blocks. You use this vector numvct again later, though, so I assume you also declared and initialized it before any of the shown code, and it probably starts off empty. Because those two numvct vectors within the if / else block pass out of scope, all the work you do to them goes away aswell. That means that when you try to use numvct again later, you're working with the (presumably) empty one that you declared at the very beginning of the program.
Instead of redeclaring numvct, try just resizing it:
//vector<int> numvct(numlen);
numvct.resize(numlen);
and
//vector<int> numvct(numlen, 0);
numvct.resize(numlen, 0);
Also you might want to try cutting down on the number of variables you're using here, and try to declare them only within the code blocks where they are really needed. It will make it easier to keep track of what's going on.
Edit: I just want to add that I suggest resizing the vectors, as opposed to any other operation you could perform on a vector, because I don't really know what your exact intended use for them was. I ran your code with these changes, as well as with the addition of ~25 other variable declarations that you did not include in your post, and it did things that seemed reasonable i.e. allowed me to choose a number, guess its digits, print number of cows and bulls etc.
As the title states i'm having trouble finding the error with the way in which my queue is being populated. It should be holding every visited state node until they have been processed. but the queue is not being populated as it should be. Can anyone help me find the bug? Below is my implementation file for the PuzzleStateNode class and source.cpp
EDIT: After more debugging it would seem that the problem lies with the following chunk of code from the solvePuzzle function. The items are never pushed to my queue, and I don't understand why. Could it be an issue with my unordered_set?
void solvePuzzle(string stateArray[3][3]) {
ofstream oFile("output.txt");
PuzzleStateNode pState(stateArray);
queue<PuzzleStateNode> puzzleQueue;
unordered_set<string> visitedPuzzleStateSet;
if (pState.parityCheck() == true) {
puzzleQueue.push(pState);
for(int i = 0; i < 31; i++){
PuzzleStateNode myTempState(puzzleQueue.front());
//puzzleQueue.pop();
if (visitedPuzzleStateSet.find(myTempState.getPuzzleID()) == visitedPuzzleStateSet.end()) { // is our value in the set? if not then do the following
visitedPuzzleStateSet.emplace(myTempState.getPuzzleID()); // add to the list of visited states.
if (myTempState.getEmptyXArrayPos() == 0 || myTempState.getEmptyXArrayPos() == 1) { // if a move to the right is available
PuzzleStateNode tempState;
tempState = PuzzleStateNode(myTempState);
tempState.moveEmptySquareRight(tempState.getEmptyXArrayPos(), tempState.getEmptyYArrayPos());
if (tempState.checkForSolve() == true) {
tempState.printState(oFile);
oFile << "Puzzle Solved in " << tempState.getMoveCounter() << " movements of the emtpy tile which are listed below." << endl;
tempState.printMoves(oFile);
cout << "Puzzle Solved!" << endl << endl << endl;
oFile.close();
return;
}
else if (tempState.checkForSolve() != true && visitedPuzzleStateSet.find(tempState.getPuzzleID()) == visitedPuzzleStateSet.end()) {
puzzleQueue.push(tempState);
}
else {
cout << "you have visited this already" << endl;
system("pause");
}
}
END EDIT:
PuzzleStateNode.h
#pragma once
#include<queue>
#include<iostream>
#include<fstream>
#include<cstdlib>
#include<string>
using namespace std;
class PuzzleStateNode
{
public:
PuzzleStateNode();
PuzzleStateNode(string tempArray[3][3]);
PuzzleStateNode(const PuzzleStateNode &other);
int getEmptyXArrayPos();
int getEmptyYArrayPos();
int getMoveCounter();
string getPuzzleID();
bool parityCheck();
bool checkForSolve();
void setPuzzleID();
void setEmptyXArrayPos(int x);
void setEmptyYArrayPos(int y);
void incrimentMoveCounter();
void pushToMoveQueue(string move);
void moveEmptySquareDown(int xEmptyPos, int yEmptyPos);
void moveEmptySquareUp(int xEmptyPos, int yEmptyPos);
void moveEmptySquareRight(int xEmptyPos, int yEmptyPos);
void moveEmptySquareLeft(int xEmptyPos, int yEmptyPos);
void printState(ofstream &oFile);
void printMoves(ofstream &oFile);
~PuzzleStateNode();
private:
string puzzleStateArray[3][3];
int moveCounter;
queue<string> moveQueue;
int emptyXArrayPos;
int emptyYArrayPos;
string puzzleID;
};
PuzzleStateNode.cpp
#include "PuzzleStateNode.h"
using namespace std;
PuzzleStateNode::PuzzleStateNode()
{
}
PuzzleStateNode::PuzzleStateNode(string tempArray[3][3])
{
puzzleID = "";
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 3; j++) {
puzzleStateArray[i][j] = tempArray[i][j];
puzzleID += tempArray[i][j];
if (puzzleStateArray[i][j] == "E") {
emptyXArrayPos = j;
emptyYArrayPos = i;
}
}
}
moveCounter = 0;
moveQueue.push("The following lists the movement of the Empty or 'E' square until the puzzle is solved: ");
}
PuzzleStateNode::PuzzleStateNode(const PuzzleStateNode &other) {
{ puzzleID = "";
moveCounter = other.moveCounter;
moveQueue = other.moveQueue;
emptyXArrayPos = other.emptyXArrayPos;
emptyYArrayPos = other.emptyYArrayPos;
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 3; j++) {
puzzleStateArray[i][j] = other.puzzleStateArray[i][j];
puzzleID += other.puzzleStateArray[i][j];
}
}
}
}
int PuzzleStateNode::getEmptyXArrayPos() {
return emptyXArrayPos;
}
int PuzzleStateNode::getEmptyYArrayPos() {
return emptyYArrayPos;
}
int PuzzleStateNode::getMoveCounter() {
return moveCounter;
}
string PuzzleStateNode::getPuzzleID() {
return puzzleID;
}
bool PuzzleStateNode::checkForSolve() {
if (puzzleStateArray[0][0] == "1" && puzzleStateArray[0][1] == "2" && puzzleStateArray[0][2] == "3" && puzzleStateArray[1][0] == "4" && puzzleStateArray[1][1] == "5" && puzzleStateArray[1][2] == "6" && puzzleStateArray[2][0] == "7" && puzzleStateArray[2][1] == "8" && puzzleStateArray[2][2] == "E") {
return true;
}
return false;
}
void PuzzleStateNode::setPuzzleID() {
puzzleID = "";
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 3; j++) {
puzzleID += puzzleStateArray[i][j];
}
}
}
void PuzzleStateNode::setEmptyXArrayPos(int x) {
emptyXArrayPos = x;
}
void PuzzleStateNode::setEmptyYArrayPos(int y) {
emptyXArrayPos = y;
}
void PuzzleStateNode::incrimentMoveCounter() {
moveCounter++;
}
void PuzzleStateNode::pushToMoveQueue(string move) {
moveQueue.push(move);
}
void PuzzleStateNode::printMoves(ofstream &oFile) {
string tempString;
for (int i = 0; i < moveQueue.size(); i++) {
cout << moveQueue.front() << endl;
moveQueue.push(moveQueue.front());
moveQueue.pop();
}
cout << endl << endl;
}
void PuzzleStateNode::printState(ofstream &oFile) {
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 3; j++) {
cout << puzzleStateArray[i][j];
}
cout << endl;
}
cout << endl;
}
void PuzzleStateNode::moveEmptySquareDown(int xEmptyPos, int yEmptyPos) {
puzzleStateArray[yEmptyPos][xEmptyPos] = puzzleStateArray[yEmptyPos + 1][xEmptyPos];
puzzleStateArray[yEmptyPos + 1][xEmptyPos] = "E";
moveQueue.push("Down");
moveCounter++;
cout << "Moving Down" << endl;
emptyYArrayPos = yEmptyPos + 1;
}
void PuzzleStateNode::moveEmptySquareUp(int xEmptyPos, int yEmptyPos) {
puzzleStateArray[yEmptyPos][xEmptyPos] = puzzleStateArray[yEmptyPos - 1][xEmptyPos];
puzzleStateArray[yEmptyPos - 1][xEmptyPos] = "E";
moveQueue.push("Up");
moveCounter++;
cout << "Moving Up" << endl;
emptyYArrayPos = yEmptyPos - 1;
}
void PuzzleStateNode::moveEmptySquareLeft(int xEmptyPos, int yEmptyPos) {
puzzleStateArray[yEmptyPos][xEmptyPos] = puzzleStateArray[yEmptyPos][xEmptyPos - 1];
puzzleStateArray[yEmptyPos][xEmptyPos - 1] = "E";
moveQueue.push("Left");
moveCounter++;
cout << "Moving Left" << endl;
emptyXArrayPos = xEmptyPos - 1;
}
void PuzzleStateNode::moveEmptySquareRight(int xEmptyPos, int yEmptyPos) {
puzzleStateArray[yEmptyPos][xEmptyPos] = puzzleStateArray[yEmptyPos][xEmptyPos + 1];
puzzleStateArray[yEmptyPos][xEmptyPos + 1] = "E";
moveQueue.push("Right");
moveCounter++;
cout << "Moving Right" << endl;
emptyXArrayPos = xEmptyPos + 1;
}
bool PuzzleStateNode::parityCheck() // counts number of swaps for a bubble sort excluding swaps involving the empty space
{
enter code here
// Puzzles with odd swaps have odd parity and are unsolvable.
string parityCheckString = "";
char tempChar;
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 3; j++) {
parityCheckString += puzzleStateArray[i][j];
}
}
int counter = 0;
for (int j = 0; j < 8; j++) {
for (int i = 0; i < 8; i++) {
if (parityCheckString[i] > parityCheckString[i + 1]) {
if (parityCheckString[i] == 'E') {
tempChar = parityCheckString[i];
parityCheckString[i] = parityCheckString[i + 1];
parityCheckString[i + 1] = tempChar;
}
else {
tempChar = parityCheckString[i];
parityCheckString[i] = parityCheckString[i + 1];
parityCheckString[i + 1] = tempChar;
counter += 1;
}
}
}
}
if (counter % 2 == 0) {
cout << "Even Parity, solving the 8 puzzle!" << endl;
return true;
}
else {
cout << "Parity is odd and puzzle is unsolvable. Skipping to next Puzzle." << endl;
return false;
}
}
PuzzleStateNode::~PuzzleStateNode()
{
}
source.cpp
#include"PuzzleStateNode.h"
#include<string>
#include<fstream>
#include<iostream>
#include<unordered_set>
using namespace std;
int main() {
void solvePuzzle(string stateArray[3][3]);
ifstream inFile("input.txt");
ofstream outFile("output.txt");
string puzNum;
int numberOfPuzzles;
string junk;
getline(inFile, puzNum); // read number of puzzles
numberOfPuzzles = stoi(puzNum); // convert value to int.
for (int i = 0; i < numberOfPuzzles; i++) {
string stateArray[3][3]; // populates a temporary puzzle state.
string temp;
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 3; j++) {
while (temp != "1" && temp != "2" && temp != "3" && temp != "4" && temp != "5" && temp != "6" && temp != "7" && temp != "8" && temp != "E") {
temp = inFile.get();
}
stateArray[i][j] = temp;
temp = inFile.get();
}
}
solvePuzzle(stateArray);
}
system("pause");
return 0;
}
void solvePuzzle(string stateArray[3][3]) {
ofstream oFile("output.txt");
PuzzleStateNode pState(stateArray);
queue<PuzzleStateNode> puzzleQueue;
unordered_set<string> visitedPuzzleStateSet;
if (pState.parityCheck() == true) {
puzzleQueue.push(pState);
for(int i = 0; i < 31; i++){
PuzzleStateNode myTempState(puzzleQueue.front());
//puzzleQueue.pop();
if (visitedPuzzleStateSet.find(myTempState.getPuzzleID()) == visitedPuzzleStateSet.end()) { // is our value in the set? if not then do the following
visitedPuzzleStateSet.emplace(myTempState.getPuzzleID()); // add to the list of visited states.
if (myTempState.getEmptyXArrayPos() == 0 || myTempState.getEmptyXArrayPos() == 1) { // if a move to the right is available
PuzzleStateNode tempState;
tempState = PuzzleStateNode(myTempState);
tempState.moveEmptySquareRight(tempState.getEmptyXArrayPos(), tempState.getEmptyYArrayPos());
if (tempState.checkForSolve() == true) {
tempState.printState(oFile);
oFile << "Puzzle Solved in " << tempState.getMoveCounter() << " movements of the emtpy tile which are listed below." << endl;
tempState.printMoves(oFile);
cout << "Puzzle Solved!" << endl << endl << endl;
oFile.close();
return;
}
else if (tempState.checkForSolve() != true && visitedPuzzleStateSet.find(tempState.getPuzzleID()) == visitedPuzzleStateSet.end()) {
puzzleQueue.push(tempState);
}
else {
cout << "you have visited this already" << endl;
system("pause");
}
}
if (myTempState.getEmptyXArrayPos() == 1 || myTempState.getEmptyXArrayPos() == 2) {
PuzzleStateNode tempState;
tempState = PuzzleStateNode(myTempState);
tempState.moveEmptySquareLeft(tempState.getEmptyXArrayPos(), tempState.getEmptyYArrayPos());
tempState.incrimentMoveCounter();
if (tempState.checkForSolve() == true) {
tempState.printState(oFile);
oFile << "Puzzle Solved in " << tempState.getMoveCounter() << " movements of the emtpy tile which are listed below." << endl;
tempState.printMoves(oFile);
cout << "Puzzle Solved!" << endl;
oFile.close();
return;
}
else if (tempState.checkForSolve() != true && visitedPuzzleStateSet.find(tempState.getPuzzleID()) == visitedPuzzleStateSet.end()) {
puzzleQueue.push(tempState);
}
else {
cout << "you have visited this state" << endl;
system("pause");
}
}
if (myTempState.getEmptyYArrayPos() == 0 || myTempState.getEmptyYArrayPos() == 1) {
PuzzleStateNode tempState;
tempState = PuzzleStateNode(myTempState);
tempState.moveEmptySquareDown(tempState.getEmptyXArrayPos(), tempState.getEmptyYArrayPos());
if (tempState.checkForSolve() == true) {
tempState.printState(oFile);
oFile << "Puzzle Solved in " << tempState.getMoveCounter() << " movements of the emtpy tile which are listed below." << endl;
tempState.printMoves(oFile);
cout << "Puzzle Solved!" << endl;
oFile.close();
return;
}
else if (tempState.checkForSolve() != true && visitedPuzzleStateSet.find(tempState.getPuzzleID()) == visitedPuzzleStateSet.end()) {
puzzleQueue.push(tempState);
}
else {
cout << "you have this state already" << endl;
system("pause");
}
}
if (myTempState.getEmptyYArrayPos() == 1 || myTempState.getEmptyYArrayPos() == 2) {
PuzzleStateNode tempState(myTempState);
tempState = PuzzleStateNode(myTempState);
tempState.moveEmptySquareUp(tempState.getEmptyXArrayPos(), tempState.getEmptyYArrayPos());
if (tempState.checkForSolve() == true) {
tempState.printState(oFile);
oFile << "Puzzle Solved in " << tempState.getMoveCounter() << " movements of the emtpy tile which are listed below." << endl;
tempState.printMoves(oFile);
cout << "Puzzle Solved!" << endl;
oFile.close();
return;
}
else if (tempState.checkForSolve() != true && visitedPuzzleStateSet.find(tempState.getPuzzleID()) == visitedPuzzleStateSet.end()) {
puzzleQueue.push(tempState);
}
else {
cout << "have visited this state already" << endl;
system("pause");
}
}
}
}
}
else
oFile.close();
return;
}
I found the problem! I was never resetting puzzle id's after copying so all puzzle states had the same ID for my set.
Can someone please help me. I am struggling to find in my code why the last value in column B always gets incremented by one. I have written some code since its an assignment due today. I also cant figure out why the last value in column B is not equal to 196 because in the reset function it sets all the values in the array to 196 . Any suggestion would be appreciated. Thank you in advance
#include <iostream> //includes cin cout
#include <iomanip>
using namespace std; //setting up the environment
const int NUMBER_OF_ROWS = 3;
const int NUMBER_OF_COLUMNS = 3;
void printAllSeats(int seats[NUMBER_OF_ROWS][NUMBER_OF_COLUMNS]);
void reset(int seats[NUMBER_OF_ROWS][NUMBER_OF_COLUMNS]);
void askForUsersSeat(int seats[NUMBER_OF_ROWS][NUMBER_OF_COLUMNS], int &SeatCountNumber, bool &anyFreeSeats);
bool isFull(int seats[NUMBER_OF_ROWS][NUMBER_OF_COLUMNS]);
bool isEmpty(int seats[NUMBER_OF_ROWS][NUMBER_OF_COLUMNS]);
int main() { //main starts
int maxSeats;
int seats[NUMBER_OF_ROWS][NUMBER_OF_COLUMNS];
int SeatCountNumber = 0;
bool anyFreeSeats;
reset(seats);
anyFreeSeats = true;
SeatCountNumber = 0;
while (anyFreeSeats) {
printAllSeats(seats);
askForUsersSeat(seats, SeatCountNumber, anyFreeSeats);
}
system("pause");
return 0;
} //main ends
void printAllSeats(int seats[NUMBER_OF_ROWS][NUMBER_OF_COLUMNS]) {
cout << endl;
cout << setw(10) << " - = Available R = Reserved\n\n";
for (int i = 0; i <= NUMBER_OF_ROWS; i++) {
cout << setw(15) << i << " ";
for (int j = 0; j < NUMBER_OF_COLUMNS; j++) {
if (i == 0) {
cout << " " << static_cast<char>(j + 65) << " ";
} else {
cout << " " << static_cast<char>(seats[i][j]) << " ";
}
}
cout << endl;
}
cout << endl;
}
void reset(int seats[NUMBER_OF_ROWS][NUMBER_OF_COLUMNS]) {
//set all values in array to 196
for (int i = 0; i <= NUMBER_OF_ROWS; i++) {
for (int j = 0; j <= NUMBER_OF_COLUMNS; j++) {
seats[i][j] = 196;
}
}
}
void askForUsersSeat(int seats[NUMBER_OF_ROWS][NUMBER_OF_COLUMNS], int &SeatCountNumber, bool &anyFreeSeats) {
int seatChoiceNumber;
char seatChoiceLetter;
int letter;
int maxSeats = NUMBER_OF_ROWS * NUMBER_OF_COLUMNS;
cout << "Seat (Row, Column): ";
cin >> seatChoiceNumber >> seatChoiceLetter;
letter = static_cast<int>(toupper(seatChoiceLetter));
if (((letter >= 65) && (letter < (65 + NUMBER_OF_COLUMNS))) && ((seatChoiceNumber > 0) && (seatChoiceNumber <= NUMBER_OF_ROWS))) {
if (seats[(seatChoiceNumber)][(letter - 65)] == 82) {
} else {
seats[(seatChoiceNumber)][(letter - 65)] = 82;
SeatCountNumber++; //this changes last value in column B for some reason
if (SeatCountNumber < maxSeats) {
anyFreeSeats = true;
}
else if (SeatCountNumber > maxSeats) {
printAllSeats(seats);
anyFreeSeats = false;
}
}
} else {
}
}
I kind of cleaned up the code a bit. It seems you found your answer in the comments, so I just did some indentation. Try and eliminate whitespaces in your code (mind you, the one I am putting here is not perfect either, but you get the point). Clean and easy to read code doesn't only make it better for you, but as you get higher up in the industry and other people begin reading and working on your code, having clean and easy to read code really helps :)
#include <iostream> //includes cin cout
#include <iomanip>
using namespace std; //setting up the environment
const int NUMBER_OF_ROWS = 3;
const int NUMBER_OF_COLUMNS = 3;
void printAllSeats(int seats[NUMBER_OF_ROWS][NUMBER_OF_COLUMNS]);
void reset(int seats[NUMBER_OF_ROWS][NUMBER_OF_COLUMNS]);
void askForUsersSeat(int seats[NUMBER_OF_ROWS][NUMBER_OF_COLUMNS], int &SeatCountNumber, bool &anyFreeSeats);
bool isFull(int seats[NUMBER_OF_ROWS][NUMBER_OF_COLUMNS]);
bool isEmpty(int seats[NUMBER_OF_ROWS][NUMBER_OF_COLUMNS]);
int main()
{
int maxSeats;
int seats[NUMBER_OF_ROWS][NUMBER_OF_COLUMNS];
int SeatCountNumber = 0;
bool anyFreeSeats;
reset(seats);
anyFreeSeats = true;
SeatCountNumber = 0;
while (anyFreeSeats)
{
printAllSeats(seats);
askForUsersSeat(seats, SeatCountNumber, anyFreeSeats);
}
system("pause");
return 0;
} //main ends
void printAllSeats(int seats[NUMBER_OF_ROWS][NUMBER_OF_COLUMNS])
{
cout << endl;
cout << setw(10) << " - = Available R = Reserved\n\n";
for (int i = 0; i <= NUMBER_OF_ROWS; i++)
{
cout << setw(15) << i << " ";
for (int j = 0; j < NUMBER_OF_COLUMNS; j++)
{
if (i == 0)
{
cout << " " << static_cast<char>(j + 65) << " ";
}
else
{
cout << " " << static_cast<char>(seats[i][j]) << " ";
}
}
cout << endl;
}
cout << endl;
}
void reset(int seats[NUMBER_OF_ROWS][NUMBER_OF_COLUMNS])
{
//set all values in array to 196
for (int i = 0; i <= NUMBER_OF_ROWS; i++)
{
for (int j = 0; j <= NUMBER_OF_COLUMNS; j++)
{
seats[i][j] = 196;
}
}
}
void askForUsersSeat(int seats[NUMBER_OF_ROWS][NUMBER_OF_COLUMNS], int &SeatCountNumber, bool &anyFreeSeats)
{
int seatChoiceNumber;
char seatChoiceLetter;
int letter;
int maxSeats = NUMBER_OF_ROWS * NUMBER_OF_COLUMNS;
cout << "Seat (Row, Column): ";
cin >> seatChoiceNumber >> seatChoiceLetter;
letter = static_cast<int>(toupper(seatChoiceLetter));
if (((letter >= 65) && (letter < (65 + NUMBER_OF_COLUMNS))) && ((seatChoiceNumber > 0) && (seatChoiceNumber <= NUMBER_OF_ROWS)))
{
if (seats[(seatChoiceNumber)][(letter - 65)] == 82)
{
}
else
{
seats[(seatChoiceNumber)][(letter - 65)] = 82;
SeatCountNumber++; //this changes last value in column B for some reason
if (SeatCountNumber < maxSeats)
{
anyFreeSeats = true;
}
else if (SeatCountNumber > maxSeats)
{
printAllSeats(seats);
anyFreeSeats = false;
}
}
}
else {
}
}
Note: Some more whitespaces could even come out but I generally like to have spaces after certain statements (personal preference).
#include "../../../std_lib_facilities.h"
int main()
{
vector <int> nmb;
vector <int> rep;
vector <int> prt;
int flag = 0;
int temp = 0;
int br = 0;
int max = -1;
int ind = 0;
cout << "Enter as much integers as you like\n";
while (cin >> temp)
{
if (nmb.size() == 0)
{
nmb.push_back(temp);
prt.push_back(temp);
++rep[br];
++br;
}
else
{
for (int i = 0; i < nmb.size(); ++i)
{
if (temp == nmb[i])
{
++rep[i];
flag = 1;
}
}
if (flag == 0)
{
nmb.push_back(temp);
prt.push_back(temp);
++rep[br];
++br;
}
else if (flag == 1)
{
flag = 0;
prt.push_back(temp);
}
}
}
cout << "You've entered numbers\n";
for (int j = 0; j < prt.size(); ++j)
cout << prt[j] << " ";
for (int k = 0; k < rep.size(); ++k)
if (rep[k] > max)
{
max = rep[k];
ind = k;
}
cout << "\n\nMost repeated number is " << nmb[ind] << endl;}
My task is to write what number has been entered max times. I know it's probably not the best idea but it was the first "good" one I had so I went with it. It compiles fine but gives me that error from that title when running. I tried cout << in few places and it seems that problem starts at the beginning of while loop.
You try to access the first element of rep, which is an empty vector.
You have to actually add elements before you may access them. Right now you're reading from and writing to memory that is not yours.
Im trying to build a minesweeper game and i keep getting a compiling error: lvalue required as left operand of assignment. only on these two lines:
#include <iostream>
#include <ctime>
using namespace std;
// ------------------------------------------------------
// class Cell
// represents one grid element in the Minesweeper game
// ------------------------------------------------------
class Cell {
public:
Cell();
void print();
void peek();
void unittest();
void setMined(bool);
bool getMined();
void setAdj(int);
private:
bool covered;
bool marked;
bool mined;
int adjcount;
};
// ------------------------
// functions for class Cell
// ------------------------
Cell::Cell(){
covered = true;
marked = false;
mined = false;
adjcount = 0;
// cout << "Creating a Cell" << endl;
}
void Cell::setAdj(int n){
adjcount = n;
}
bool Cell::getMined(){
return mined;
}
void Cell::setMined(bool b){
mined = b;
}
void Cell::print(){
if (marked) cout << " L ";
else {
if (covered) cout << " ? ";
else{
if (mined) cout << " # ";
else if (adjcount == 0) cout << " _ ";
else cout << " " << adjcount << " ";
}
}
}
void Cell::peek(){
if (mined) cout << " # ";
else if (adjcount == 0) cout << " _ ";
else cout << " " << adjcount << " ";
}
void Cell::unittest(){
print(); cout << endl;
covered = false;
print(); cout << endl;
adjcount = 4;
print(); cout << endl;
mined = true;
print(); cout << endl;
covered = true;
print(); cout << endl;
marked = true;
print(); cout << endl;
}
// -------------------------------------
// class Board
// this class represents a 2 dimensional
// array of Cell objects for the game
// of minesweeper
//--------------------------------------
class Board{
public:
Board();
void print();
void peek();
void adjacencycount();
void mixMined();
private:
static const int rows = 5;
static const int cols = 5;
Cell cells [rows][cols];
int mines;
};
// --------------------------
// functions for class Board
// --------------------------
Board::Board(){
mines = 6;
for(int i = 0; i < 1 ; i++){
for(int j = 0; j < mines; j++){
cells[i][j].setMined(true);
}
}
}
void Board::mixMined(){
int shuffle = 1000;
for(int i = 0; i < shuffle; i++){
int r1 = (rand()%rows);
int c1 = (rand()%cols);
int r2 = (rand()%rows);
int c2 = (rand()%cols);
if(r1 && c1 != r2 && c2){
bool temp = cells[r1][c1].getMined();
cells[r1][c1].getMined() = cells[r2][c2].getMined();
cells[r2][c2].getMined() = temp;
}
}
}
void Board::adjacencycount(){
for( int i = 0; i < rows; i++){
for( int j = 0; j < cols; j++){
if(!cells[i][j].getMined()){
int count = 0;
if (i-1 >= 0 && j-1 >= 0 && cells[i-1][j-1].getMined()) count++;
if (i-1 >= 0 && cells[i-1][j].getMined()) count++;
if (i-1 >= 0 && j+1 <= cols-1 && cells[i-1][j+1].getMined()) count++;
if (j-1 >= 0 && cells[i][j-1].getMined()) count++;
if (j+1 <= cols-1 && cells[i][j+1].getMined()) count++;
if (i+1 <= rows-1 && j-1 >= 0 && cells[i+1][j-1].getMined()) count++;
if (i+1 <= rows-1 && cells[i+1][j].getMined()) count++;
if (i+1 <= rows-1 && j+1 <= cols-1 && cells[i+1][j+1].getMined()) count++;
cells[i][j].setAdj(count);
// cout << count; -- for testing purposes
}
}
}
}
void Board::print(){
for (int i = 0; i < rows; i++){
for (int j = 0; j < cols; j++){
cells[i][j].print();
}
cout << endl << endl;
}
}
void Board::peek(){
for (int i = 0; i < rows; i++){
for (int j = 0; j < cols; j++){
cells[i][j].peek();
}
cout << endl << endl;
}
}
// -------------------------
// main function for testing
// -------------------------
int main(void) {
//Cell c;
//c.unittest();
srand(time(0));
Board b;
b.mixMined();
b.adjacencycount();
b.peek();
return 0;
}
I'm trying to get my cells to swap, so that the mines would randomize every new game. Ive searched around and couldn't find a solution to this. I added "==" but that function isn't going to do what i want it to.
++EDIT++ I'm sorry it did state lvalue required, i missed typed that
minesweeper.cpp: In member function ‘void Board::mixMined()’:
minesweeper.cpp:130: error: lvalue required as left operand of assignment
minesweeper.cpp:131: error: lvalue required as left operand of assignment
Thats the error that occurs.
I think getMined() is actually something like this:
bool getMined()
So you are trying to assign to rValue which is not possible
You might want to write some function like:
void setMined(bool m) and the use it like:
cells[r1][c1].setMined( cells[r2][c2].getMined() );