How to check if an array equals any other array C++? - c++

I'm trying to make a dice program in C++. In that program, I have a function called "bool_if" (Don't ask me why I named some things the way I did, I made this program for me and I don't want to change variable/function names). I want bool_if() to check if any elements in the array rolled_die[] is the same.
Sorry if that doesn't make sense, here's the source code (I commented in part of the source code for what I want):
#include <cstdlib>
#include <ctime>
#include <iostream>
#include <unistd.h>
#include <fstream>
using namespace std;
void clear()
{
cout<<"\033[2J\033[1;1H";
}
bool rolled_die[5];
void dice() {
if (die[0] == die[1] || die[0] == die[2] || die[0] == die[3] || die[0] == die[4] || die[0] == die[5]) {
rolled_die[0] = true
}
else if (die[1] == die[2] || die[1] == die[3] || die[1] == die[4] || die[1] == die[5]) {
rolled_die[1] = true
}
else if (die[2] == die[3] || die[2] == die[4] || die[2] == die[5]) {
rolled_die[2] = true
}
else if (die[3] == die[4] || die[3] == die[5]) {
rolled_die[3] = true
}
else if (die[4] == die[5]) {
rolled_die[4] = true
}
}
int finished_score = 0
void bool_if {
if (rolled_die[0] == true || rolled_die[1] == true || rolled_die[2] == true || rolled_die[3] == true || rolled_die[4] == true) {
finished_score++;
}
/* In this part, I need to check if rolled_die[0] is equal to rolled_die[1], or rolled_die[2], etc all the way up to rolled_die[5]. */
int main()
{
srand(time(0));
int die[6] = { (rand()%6)+1,(rand()%6)+1, (rand()%6)+1, (rand()%6)+1, (rand()%6)+1, (rand()%6)+1 };
int bet;
ifstream a_file ("Score.txt");
if ( !a_file.is_open() ) {
clear();
cout<<"Score file could not be loaded. Maybe file doesn't exist?\n";
return 0;
}
int score;
a_file>> score;
clear();
cout<<"How much would you like to bet?\nRemember, you only have $"<< score <<"!\nEnter your bet: ";
cin>> bet;
if ( bet > score ) {
clear();
cout<<"You bet more money then you have!\n";
return 0;
}
clear();
cout<<"Rolling...\n";
usleep(0.1 * 1000000);
cout<<"First die: " << die[0] <<"\n";
usleep(1.3 * 1000000);
cout<<"Second die: " << die[1] <<"\n";
usleep(0.3 * 1000000);
cout<<"Third die: " << die[2] <<"\n";
usleep(2 * 1000000);
cout<<"Fourth die: " << die[3] <<"\n";
usleep(0.3 *1000000);
cout<<"Fifth die: " << die[4] <<"\n";
usleep(1.2 * 1000000);
cout<<"Sixth die: " << die[5] <<"\n";
cout<<"\n\nPress enter to see how you fared.";
cin.get();
clear();
return 0;
}
Also please tell the function dice() doesn't work. I want dice() to check for any pairs.

int die[6] = { (rand()%6)+1,(rand()%6)+1, (rand()%6)+1, (rand()%6)+1, (rand()%6)+1, (rand()%6)+1 };
Replace that with this:
int die[6] = {1, 2, 3, 4, 5, 6};
std::random_shuffle(die, die+6);
The Code below runs just fine for me: http://ideone.com/F4Eefj

You can dramatically simplify this code by using for loops. For example, this compares every index of the array to every index after that one (which appears to be what you're doing manually):
#include <iostream>
int main(int argc, char** argv) {
int die[] = { 4, 5, 6, 4, 5, 3 };
const size_t LENGTH = 6;
for(size_t i = 0; i < LENGTH; ++i) {
for(size_t j = i + 1; j < LENGTH; ++j) {
if(die[i] == die[j]) {
std::cout << "Found a pair at (" << i << ", " << j << ")" << std::endl;
}
}
}
return 0;
}
Your dice() function seems to do this, but you're not calling it anywhere.

Related

How would I fix this whitespace from appearing on the sides whenever I am showing the snakes length?

Whenever I run my program I check to see if I would place down 3 os it goes to the right. I know that the problem is that I have a bunch of if statements that cycle through, but I have a for loop there to place down the snakes trail. I know that all those ifs aren't good.
I tried changing in the top of the for loop to be a if statement that was always true, it didn't work nothing did. I am confused on how to check for all of the coordinates, but still not have the walls pop up on the sides.
I am a begginer, so don't hate on my code that much.
snake.cpp
#include <iostream>
#include <conio.h>
#include <random>
#include <time.h>
#include "snake.hpp"
void endGame(int score);
const int KEY_ARROW_CHAR1 = 224;
const int KEY_ARROW_UP = 72;
const int KEY_ARROW_DOWN = 80;
const int KEY_ARROW_LEFT = 75;
const int KEY_ARROW_RIGHT = 77;
void snake::input() {
// checks for arrow key input
if (_kbhit()) {
//stores keycode
int key = _getch();
//checks if key is arrow key
if (key == KEY_ARROW_CHAR1) {
//stores arrow key
key = _getch();
//checks if arrow key is up
if (key == KEY_ARROW_UP) {
direction = '^';
}
//checks if arrow key is down
else if (key == KEY_ARROW_DOWN) {
direction = 'v';
}
//checks if arrow key is left
else if (key == KEY_ARROW_LEFT) {
direction = '<';
}
//checks if arrow key is right
else if(key == KEY_ARROW_RIGHT) {
direction = '>';
}
}
}
switch (direction) {
case '^':
snakeCoords[2]--;
break;
case 'v':
snakeCoords[2]++;
break;
case '>':
snakeCoords[0]++;
break;
case '<':
snakeCoords[0]--;
}
checkForObjects();
}
bool snake::checkForObjects() {
if ((snakeCoords[0] == 40 || snakeCoords[0] == 0) || (snakeCoords[2] == 20 || snakeCoords[2] == 0)) {
endGame(score);
}
if (snakeCoords[0] == fruitCoords[0] && snakeCoords[2] == fruitCoords[2]) {
score++;
getFruitLoc();
return true;
}
return false;
}
void snake::getFruitLoc() {
srand(time(0));
fruitCoords[0] = rand() % 39;
fruitCoords[2] = rand() % 19;
}
void endGame(int score) {
std::cout << "you died, your score was " << score;
exit(0);
}
```
#include <iostream>
#include <conio.h>
#include <random>
#include "snake.hpp"
#include <vector>
void createArena(char direction);
//Coordinates for snake
std::vector <std::vector<int>> previousCoords{
{14, 10},
{13, 10},
{12, 10}
};
snake coordManager{};
int score{0};
int main()
{
//make terminal green
system("color 0a");
while (true) {
std::cout << "\t" << score;
//pushes ascii arena down
for (size_t i{}; i <= 5; i++) {
std::cout << std::endl;
}
score = coordManager.score;
//updates snake based on coordinates
createArena(coordManager.direction);
//manages all snake movements
coordManager.input();
//reminder this clears the screan
system("CLS");
}
}
void createArena(char direction) {
//offsets screen
std::cout << "\t\t\t\t";
for (size_t y{}; y <= 20; y++) {
for (size_t x{}; x <= 40; x++) {
//checks if it hits the snakes coordinates
for (size_t i{}; i < previousCoords.size();) {
if (x == previousCoords.at(i).at(0) && y == previousCoords.at(i).at(1)) {
std::cout << "O";
}
i++;
}
if (coordManager.snakeCoords[0] == x && coordManager.snakeCoords[2] == y) {
std::cout << direction;
}
else if (x == 0 || x == 40) {
std::cout << '|';
}
else if (y == 0 || y == 20) {
std::cout << '-';
}
else if(coordManager.fruitCoords[0] == x && coordManager.fruitCoords[2] == y) {
std::cout << "F";
}
else {
std::cout << " ";
}
}
//offsets again
std::cout << std::endl << "\t\t\t\t";
}
}
#include <conio.h>
#include <random>
#include <time.h>
class snake {
public:
void input();
bool checkForObjects();
int score{};
int snakeCoords[2]{
/* X */ 15,
/* Y */ 10
};
int fruitCoords[2]{
/* X */ rand() % 39,
/* Y */ rand() % 19
};
char direction{'O'};
private:
void getFruitLoc();
};
https://i.stack.imgur.com/bdSNf.png
I got it working, I used a boolean that I would change if it was different from whitespace. it was a simple fix sorry.

While Overloading The << Operator Was It Correctly Formatted?

I have been getting outputs and sometimes even getting the complete output, however I don't quite understand why I'd be getting said outputs. I want to believe it has something to do with my overloading of said operator "<<" when I perform the operation of outputting the information in the "OpenSea" object. Any leads would be tremendously helpful and thank you for your time!
Note: I included only the necessary files but will update if you think you need more to understand the full scope of my situation. Also there is no need to give me tips on how to format my code as I know a lot of it can be reworked for optimization.
main.cpp
#include "aquaClasses.h"
#include "aquaFish.h"
#include "aquaKillerWhale.h"
#include "aquaPenguin.h"
#include "aquaSea.h"
using namespace std;
int main ()
{
srand (time (NULL));
// Simulation
Sea OpenSea (17, 17);
cout << OpenSea;
}
aquaClasses.h <-- "main" header file
#ifndef AQUACLASSES_H
#define AQUACLASSES_H
#include <cmath>
#include <cstdlib>
#include <cstring>
#include <ctime>
#include <iostream>
#include <iomanip>
// Constants
const short int AMT_FISH = 200;
const short int AMT_KWHALES = 2;
const short int AMT_PENGS = 50;
const short int MAX_SIM_INTERATIONS = 10000;
const short int MAX_SEA_GRID = 25;
const short int MAX_SEA_SIZE = 625;
// Functions
template <typename TYPE> int calculate_distance (int obj1_x, int obj1_y,
TYPE obj2);
template <typename TYPE> int calculate_direction (int obj1_x, int obj1_y,
TYPE obj2);
#endif
aquaSea.h
#ifndef AQUASEA_H
#define AQUASEA_H
// Forward Declarations to circumvent circular dependency
class Fish;
class Penguin;
class Killer_Whale;
class Sea
{
private:
char m_grid [MAX_SEA_GRID][MAX_SEA_GRID];
int m_fish;
int m_kwhales;
int m_pengs;
int m_size;
int m_height;
int m_width;
void clear ();
void populate ();
public:
Sea (const int grid_size_height, const int grid_size_width);
friend std::ostream &operator<<(std::ostream &os, Sea obj);
int getHeight () const {return m_height;};
int getWidth () const {return m_width;};
void setCell (int obj_x, int obj_y, char cell_symbol);
// Appropriate accessor/mutator functions
};
#endif
aquaSea.cpp
#include "aquaClasses.h"
#include "aquaFish.h"
#include "aquaPenguin.h"
#include "aquaKillerWhale.h"
#include "aquaSea.h"
using namespace std;
// - [row][column]
Sea::Sea (const int grid_size_height, const int grid_size_width)
{
m_fish = 200;
m_kwhales = 2;
m_pengs = 50;
if ((grid_size_height || grid_size_width) <= 0)
{
if (grid_size_height <= 0 && grid_size_width > 0)
{
m_size = MAX_SEA_GRID * grid_size_width;
m_width = grid_size_width;
m_height = MAX_SEA_GRID;
}
else if (grid_size_width <= 0 && grid_size_height > 0)
{
m_size = MAX_SEA_GRID * grid_size_height;
m_width = MAX_SEA_GRID;
m_height = grid_size_height;
}
else if (grid_size_height <= 0 && grid_size_width <= 0)
{
m_size = MAX_SEA_GRID * MAX_SEA_GRID;
m_height = MAX_SEA_GRID;
m_width = MAX_SEA_GRID;
}
}
else
{
m_size = grid_size_height * grid_size_width;
m_height = grid_size_height;
m_width = grid_size_width;
}
clear ();
populate ();
}
ostream &operator<<(ostream &os, Sea obj)
{
os << "Sea Height: " << obj.m_width << endl << "Sea Wdith: "
<< obj.m_width << endl << "Sea Size: " << obj.m_size
<< endl;
os << "Grid View: " << endl;
for (int i = 0; i < obj.m_height; i++)
{
for (int j = 0; j < obj.m_width; j++)
{
os << obj.m_grid [i][j];
}
os << endl;
}
return os;
}
void Sea::clear ()
{
for (int i = 0; i < m_height; i++)
{
for (int j = 0; j < m_width; j++)
{
m_grid[i][j] = 'O';
}
}
return;
}
void Sea::populate ()
{
// Special simluation variables
bool applyFish = true;
bool applyKWhales = false;
bool applyPengs = false;
int amtFishPop = 35;
int amtKWhalesPop = 2;
int amtPengPop = 20;
int index = 0;
int randGridRow = 0;
int randGridCol = 0;
int totalPop = amtFishPop + amtKWhalesPop + amtPengPop;
Fish arr_fish [AMT_FISH];
Killer_Whale arr_kwhales [AMT_KWHALES];
Penguin arr_pengs [AMT_PENGS];
for (int i = 0; i < totalPop; i++)
{
// Grab random place on grid to apply and check if grid plot is open
randGridRow = rand () % 16;
randGridCol = rand () % 16;
while (m_grid [randGridRow][randGridCol] != 'O')
{
randGridRow = rand () % 16;
randGridCol = rand () % 16;
}
// Populate and Update Fish
if (amtFishPop > 0 && applyFish == true)
{
arr_fish[index].setX (randGridCol);
arr_fish[index].setY (randGridRow);
setCell (arr_fish[index].getX (), arr_fish[index].getY (), 'F');
amtFishPop--;
index++;
}
else if (amtFishPop == 0)
{
applyFish = false;
applyKWhales = true;
index = 0;
}
// Populate and Update Killer Whales
if (amtKWhalesPop > 0 && applyKWhales == true)
{
arr_kwhales[index].setX (randGridCol);
arr_kwhales[index].setY (randGridRow);
setCell (arr_kwhales[index].getX (), arr_kwhales[index].getY (), 'K');
amtKWhalesPop--;
index++;
}
else if (amtKWhalesPop == 0)
{
applyKWhales = false;
applyPengs = true;
index = 0;
}
// Populate and Update Penguins
if (amtPengPop > 0 && applyPengs == true)
{
arr_pengs[index].setX (randGridCol);
arr_pengs[index].setY (randGridRow);
setCell (arr_pengs[index].getX (), arr_pengs[index].getY (), 'P');
amtPengPop--;
index++;
}
else if (amtPengPop == 0)
{
applyPengs = false;
index = 0;
}
}
return;
}
void Sea::setCell (int obj_x, int obj_y, char cell_symbol)
{
m_grid [obj_x][obj_y] = cell_symbol;
return;
}
Types of Output
Wanted:
- Image
Unwanted:
- Image
STOP! AFTER THIS POINT IS OPTIONAL CODE TO FURTHER UNDERSTAND THE SITUATION
Other Code Of Reference If You Want But I Don't Think It's Needed
aquaFish.h
#ifndef AQUAFISH_H
#define AQUAFISH_H
class Fish
{
private:
int m_fish_amt_food;
int m_fish_x;
int m_fish_y;
bool m_fish_alive;
public:
Fish ();
int getX () const {return m_fish_x;};
int getY () const {return m_fish_y;};
void setX (int new_x) {m_fish_x = new_x;};
void setY (int new_y) {m_fish_y = new_y;};
int getFishAmtFood () const {return m_fish_amt_food;};
void move ();
};
#endif
aquaFish.cpp
#include "aquaClasses.h"
#include "aquaFish.h"
using namespace std;
Fish::Fish ()
{
int randNum = rand () % 10 + 1;
m_fish_amt_food = randNum;
m_fish_x = -1;
m_fish_y = -1;
}
void Fish::move ()
{
int randDir = rand () % 8 + 1;
if (randDir == 1)
{
m_fish_y++;
}
else if (randDir == 2)
{
m_fish_x++;
m_fish_y++;
}
else if (randDir == 3)
{
m_fish_x++;
}
else if (randDir == 4)
{
m_fish_x++;
m_fish_y--;
}
else if (randDir == 5)
{
m_fish_y--;
}
else if (randDir == 6)
{
m_fish_x--;
m_fish_y--;
}
else if (randDir == 7)
{
m_fish_x--;
}
else if (randDir == 8)
{
m_fish_x--;
m_fish_y++;
}
return;
}
aquaPenguin.h
#ifndef AQUAPENGUIN_H
#define AQUAPENGUIN_H
// Forward Declarations to circumvent circular dependancy
class Sea;
class Fish;
class Killer_Whale;
class Penguin
{
private:
int m_peng_health; // 0-100
int m_peng_x;
int m_peng_y;
bool m_peng_alive;
public:
Penguin ();
int getX () const {return m_peng_x;};
int getY () const {return m_peng_y;};
void setX (int new_x) {m_peng_x = new_x;};
void setY (int new_y) {m_peng_y = new_y;};
void move (Sea obj_sea, Fish arr_fish [], int arr_fish_size,
Killer_Whale arr_kwhale [], int arr_kwhale_size);
};
#endif
aquaPenguin.cpp
#include "aquaClasses.h"
#include "aquaFish.h"
#include "aquaKillerWhale.h"
#include "aquaPenguin.h"
#include "aquaSea.h"
#include "aquaFunctions.cpp"
using namespace std;
Penguin::Penguin ()
{
m_peng_health = rand () % (81 - 60) + 60;
m_peng_x = -1;
m_peng_y = -1;
m_peng_alive = false;
}
void Penguin::move (Sea obj_sea, Fish arr_fish [], int arr_fish_size,
Killer_Whale arr_kwhale [], int arr_kwhale_size)
{
int actuDistToFish = 8;
int currDistToFish = 0;
int tempMoveX = 0;
int tempMoveY = 0;
int amtMove = 0;
int direction = 0;
int fishIndex = 0;
bool moveAwayKillerWhale = false;
bool fishInRange = false;
// Determine amount of cells to move in sea
if (m_peng_health >= 81 && m_peng_health <= 100)
{
amtMove = 5;
}
else if (m_peng_health >= 61 && m_peng_health <= 80)
{
amtMove = 4;
}
else if (m_peng_health >= 41 && m_peng_health <= 60)
{
amtMove = 3;
}
else if (m_peng_health >= 21 && m_peng_health <= 40)
{
amtMove = 2;
}
else if (m_peng_health >= 1 && m_peng_health <= 20)
{
amtMove = 1;
}
else
{
cout << "Chicken of the sea at: " << m_peng_x << " " << m_peng_y
<< endl;
return;
}
// ADD: Find if any killer whales are near first and if so then penguin just moves away
// Find if any fish are near <-- THIS IS WRONG, YOU NEED TO FIND THE CLOSEST FISH
for (int i = 0; i < arr_fish_size; i++)
{
currDistToFish = calculate_distance (m_peng_x, m_peng_y,
arr_fish[i]);
if (currDistToFish <= 8)
{
if (currDistToFish < actuDistToFish)
{
actuDistToFish = currDistToFish;
fishIndex = i;
fishInRange = true;
}
}
}
// ADD: If fish and whale are found do something, we decide. Otherwise move randomly Peng See Dist 8.0
// ADD Move 1 tick then gauge situation again
for (int k = 0; k < amtMove; k++)
{
if (fishInRange == true && moveAwayKillerWhale == false)
{
tempMoveX = m_peng_x; // temp used for storing before changing
tempMoveY = m_peng_y; // temp used for storing before changing
direction = calculate_direction (m_peng_x, m_peng_y,
arr_fish[fishIndex]);
cout << "Penguin pos before moving: " << m_peng_x << ","
<< m_peng_y << endl;
cout << "Closest Fish pos: " << arr_fish[fishIndex].getX () << ","
<< arr_fish[fishIndex].getY () << endl;
if (m_peng_health == 0)
{
cout << "Chicken of the sea at: " << m_peng_x << " " << m_peng_y
<< endl;
return;
}
if (direction == 1)
{
actuDistToFish--;
m_peng_health--;
tempMoveY++;
}
else if (direction == 2)
{
actuDistToFish--;
m_peng_health--;
tempMoveX++;
tempMoveY++;
}
else if (direction == 3)
{
actuDistToFish--;
m_peng_health--;
tempMoveX++;
}
else if (direction == 4)
{
actuDistToFish--;
m_peng_health--;
tempMoveX++;
tempMoveY--;
}
else if (direction == 5)
{
actuDistToFish--;
m_peng_health--;
tempMoveY--;
}
else if (direction == 6)
{
actuDistToFish--;
m_peng_health--;
tempMoveX--;
tempMoveY--;
}
else if (direction == 7)
{
actuDistToFish--;
m_peng_health--;
tempMoveX--;
}
else if (direction == 8)
{
actuDistToFish--;
m_peng_health--;
tempMoveX--;
tempMoveY++;
}
else
{
cout << "[ERROR]: Penguin direction messed up." << endl;
}
// MODIFY: Lastly check if out of bounds and then move peng
if (tempMoveX > obj_sea.getWidth ()
|| tempMoveX < -(obj_sea.getWidth ()))
{
m_peng_x = m_peng_x; // AKA dont move
m_peng_y = m_peng_y;
}
else if (tempMoveY > obj_sea.getHeight ()
|| tempMoveY < -(obj_sea.getHeight ()))
{
m_peng_x = m_peng_x; // AKA dont move
m_peng_y = m_peng_y;
}
else
{
obj_sea.setCell (m_peng_x, m_peng_y, 'O'); // Delete old cell
m_peng_x = tempMoveX;
m_peng_y = tempMoveY;
obj_sea.setCell (m_peng_x, m_peng_y, 'P'); // Set new cell
}
// Check if peng eats after moving
if (actuDistToFish == 0)
{
// Stop moving
amtMove = 0;
// Eat fish
m_peng_health += arr_fish[fishIndex].getFishAmtFood ();
// ADD: Remove fish from grid
}
cout << "Penguin pos after moving: " << m_peng_x << ","
<< m_peng_y << endl;
}
else if (fishInRange == false && moveAwayKillerWhale == true)
{
}
else if (fishInRange == false && moveAwayKillerWhale == false)
{
// If no fish, movement is random, else it's towards fish how ever many
// step the penguin can go
direction = rand () % 8 + 1;
if (direction == 1)
{
m_peng_y++;
}
else if (direction == 2)
{
m_peng_x++;
m_peng_y++;
}
else if (direction == 3)
{
m_peng_x++;
}
else if (direction == 4)
{
m_peng_x++;
m_peng_y--;
}
else if (direction == 5)
{
m_peng_y--;
}
else if (direction == 6)
{
m_peng_x--;
m_peng_y--;
}
else if (direction == 7)
{
m_peng_x--;
}
else if (direction == 8)
{
m_peng_x--;
m_peng_y++;
}
else
{
cout << "[ERROR]: Penguin random direction messed up." << endl;
}
}
}
return;
}
aquaKillerWhale.h
#ifndef AQUAKILLERWHALE_H
#define AQUAKILLERWHALE_H
class Penguin;
class Killer_Whale
{
private:
int m_kwhale_amt_pengs;
int m_kwhale_x;
int m_kwhale_y;
public:
Killer_Whale ();
int getX () const {return m_kwhale_x;};
int getY () const {return m_kwhale_y;};
void setX (int new_x) {m_kwhale_x = new_x;};
void setY (int new_y) {m_kwhale_y = new_y;};
void move (Penguin arr_peng []);
};
#endif
aquaKillerWhale.cpp
#include "aquaClasses.h"
#include "aquaKillerWhale.h"
#include "aquaPenguin.h"
using namespace std;
Killer_Whale::Killer_Whale ()
{
m_kwhale_x = -1;
m_kwhale_y = -1;
}
void Killer_Whale::move (Penguin arr_peng [])
{
return;
}
aquaFunctions.cpp
#include "aquaClasses.h"
using namespace std;
// Functions
template <typename TYPE>
int calculate_direction (int obj1_x, int obj1_y, TYPE obj2)
{
int calculatedX = obj2.getX () - obj1_x;
int calculatedY = obj2.getY () - obj1_y;
int direction = 0;
if (calculatedX == 0 && calculatedY > 0)
{
direction = 1;
}
else if (calculatedX > 0 && calculatedY > 0)
{
direction = 2;
}
else if (calculatedX > 0 && calculatedY == 0)
{
direction = 3;
}
else if (calculatedX > 0 && calculatedY < 0)
{
direction = 4;
}
else if (calculatedX == 0 && calculatedY < 0)
{
direction = 5;
}
else if (calculatedX < 0 && calculatedY < 0)
{
direction = 6;
}
else if (calculatedX < 0 && calculatedY == 0)
{
direction = 7;
}
else if (calculatedX < 0 && calculatedY > 0)
{
direction = 8;
}
else
{
cout << "[ERROR]: Direction calculation failed." << endl;
}
return direction;
}
template <typename TYPE>
int calculate_distance (int obj1_x, int obj1_y, TYPE obj2)
{
int distance = sqrt ((obj1_x - obj2.getX ())
* (obj1_x - obj2.getX ())
+ (obj1_y - obj2.getY ())
* (obj1_y - obj2.getY ()));
return distance;
}

undefined reference error: `ClassName:: ClassMember`

Why my program is getting these errors?
undefined reference to `PizzaOrder::toppings_offered'
undefined reference to `PizzaOrder::arraySize'
undefined reference to `PizzaOrder::base_price'
undefined reference to `PizzaOrder::MedPizBase'
undefined reference to `PizzaOrder::base_price'
undefined reference to `PizzaOrder::LargePizBase'
...
This is my program:
#include <iostream>
#include <string>
#include <sstream>
using namespace std;
class PizzaOrder
{
private:
int size;
int num_toppings;
string toppings[100];
public:
static const string toppings_offered[];
static const double topping_base_cost;
static const double base_price;
static const string defaultSize;
static const double MedPizBase;
static const double LargePizBase;
static const int arraySize;
PizzaOrder();
PizzaOrder(int size);
// MUTATORS & ACCESSORS & METHODS
int GetSize() { return size; }
int GetNumToppings() { return num_toppings; }
string GetToppings();
void GetPrice();
bool SetSize(int size);
void AddTopping(string topping);
void AddTopping(int n); //int represents position in array toppings_offered[]
string StringizeSize(int size);
void DisplayPizza();
};
const string toppings_offered[] = {"1. Onions", "2. Bell Peppers",
"3. Olives", "4. Pepperoni", "5. Sausage",
"6. Mushrooms", "7. Jalapenos"};
const string defaultSize = "Small ";
const double topping_base_cost = 1;
const double base_price = 7;
const double MedPizBase = 0.15;
const double LargePizBase = 0.25;
const int arraySize = sizeof(toppings_offered)/sizeof(toppings_offered[0]);
PizzaOrder::PizzaOrder()
{
SetSize(0);
}
PizzaOrder::PizzaOrder(int size)
{
if (!SetSize(size))
SetSize(0);
}
string PizzaOrder::StringizeSize(int size)
{
string pizzaSize;
if (size == 0)
pizzaSize = "Small";
if (size == 1)
pizzaSize = "Medium";
if (size == 2)
pizzaSize = "Large";
return pizzaSize;
}
bool PizzaOrder::SetSize(int size)
{
if (size != 0 && size != 1
&& size != 2)
return false;
this->size = size;
return true;
}
void PizzaOrder::AddTopping(string topping) // totally wrong
{
for (int i = 0; i < arraySize; i++)
{
if (topping == toppings_offered[i])
{
toppings[num_toppings] = topping;
num_toppings++;
}
}
}
void PizzaOrder::AddTopping(int n) //increments n by 1 for each valid topping chosen
{
if (n > 0 && n < 7)
n++;
n = num_toppings;
}
string PizzaOrder::GetToppings()
{
string result;
for(int i = 0; i < GetNumToppings(); i++)
{
result += toppings[i];
}
return result;
}
void PizzaOrder::DisplayPizza()
{
cout << "Your pizza order: " << PizzaOrder::StringizeSize(GetSize()) << ", "
<< PizzaOrder::GetNumToppings() << ", "
<< PizzaOrder::GetToppings();
}
void PizzaOrder::GetPrice()
{
double TotalPizPrice;
double MedPizzaPrice = base_price+(base_price*MedPizBase);
double LargePizzaPrice = base_price+(base_price*LargePizBase);
double topPrice = (GetNumToppings()*topping_base_cost);
if (GetSize() == 0)
TotalPizPrice = topPrice+base_price;
if (GetSize() == 1)
TotalPizPrice = topPrice+MedPizzaPrice;
if (GetSize() == 2)
TotalPizPrice = topPrice+LargePizzaPrice;
cout << "Your pizza's total price is: $" << TotalPizPrice;
}
int main()
{
PizzaOrder pizza;
string choice;
char selection;
int topChoice;
do
{
cout << "Size of pizza (Small, Medium, Large) or Quit?\n" << endl;
getline(cin, choice);
selection = choice[0];
if (selection == 'S' || selection == 's')
pizza.SetSize(0);
if (selection == 'M' || selection == 'm')
pizza.SetSize(1);
if (selection == 'L' || selection == 'l')
pizza.SetSize(2);
do
{
cout << "Current pizza: "
<< pizza.StringizeSize(pizza.GetSize())
<< pizza.GetToppings() << "\n"
<< "Select an item by number (0 when done):\n" << endl;
for (int i = 0; i < 8; i++)
{
cout << toppings_offered[i] << "\n";
}
cout <<"\nSelection: ";
cin >> topChoice;
pizza.AddTopping(topChoice);
}
while (topChoice != 0);
}
while(selection != 'q' && selection != 'Q');
pizza.DisplayPizza();
pizza.GetPrice();
return 0;
}
The definition of static member variables is wrong, they should be:
const string PizzaOrder::defaultSize = "Small ";
~~~~~~~~~~~~
...
Otherwize they'll be just global variables.

Hanoi Iterative solution

I am attempting to implement the Tower of Hanoi iterative solution in c++ as noted in Wikepedia
Simpler statement of iterative solution
Alternating between the smallest and the next-smallest disks, follow the steps for the appropriate case:
For an even number of disks:
*make the legal move between pegs A and B*
*make the legal move between pegs A and C*
*make the legal move between pegs B and C*
*repeat until complete*
For an odd number of disks:
*make the legal move between pegs A and C*
*make the legal move between pegs A and B*
*make the legal move between pegs C and B*
*repeat until complete*
In each case, a total of 2n-1 moves are made.
The code I have written thus far is
#include <iostream>
#include <list>
const int SIZE = 5;
int pCount = 1;
using namespace std;
list<int> *lhs;
list<int> *mid;
list<int> *rhs;
void initTower(int size);
void printPeg(list<int> p);
bool printTower();
bool isEven(list<int> l);
bool move(list<int> *from, list<int> *to);
int main() {
lhs = new list<int>;
mid = new list<int>;
rhs = new list<int>;
initTower(SIZE);
printTower();
bool run = true;
while (run) {
int n = SIZE;
if (n % 2 == 0) // even
{
move(lhs,mid);
move(lhs,rhs);
move(mid,rhs);
}else{
move(lhs,rhs);
move(lhs,mid);
move(rhs,mid);
}
if (rhs->size() == SIZE) {
run = false;
}
}
return 0;
}
bool isEven(list<int> l) {
return l.size() % 2 == 0;
}
void initTower(int size) {
while (size--)
lhs->push_back(size + 1);
}
void printPeg(list<int> p) {
if (p.empty()) {
cout << "empty" << endl;
} else {
for (int i: p)
cout << i << " ";
cout << endl;
}
}
bool printTower() {
cout << "==============" << endl;
cout << "=====top=======" << pCount++ << endl;
printPeg(*lhs);
printPeg(*mid);
printPeg(*rhs);
cout << "==============" << endl << endl;
return true;
}
bool move(list<int> *from, list<int> *to) {
bool vailidMove = false;
int fVal = 0;
int toVal = 0;
if (!from->empty())
fVal = from->back();
if (!to->empty())
toVal = to->back();
if ((fVal < toVal || toVal == 0) && (fVal > 0 && fVal != 0)) {
from->pop_back();
to->push_back(fVal);
vailidMove = true;
printTower();
}
return vailidMove;
}
my output to the above program is.
==============
=====top=======1
5 4 3 2 1
empty
empty
==============
==============
=====top=======2
5 4 3 2
empty
1
==============
==============
=====top=======3
5 4 3
2
1
==============
==============
=====top=======4
5 4 3
2 1
empty
==============
==============
=====top=======5
5 4
2 1
3
==============
What am I overlooking? Any advise is helpful.
I added one condition in your move function to move poles if fVal > toVal (or you would stop instead of finishing the algorithm).
I alternated the source and destination half the time, as this is said in the wiki article you were referring to.
Alternating between the smallest and the next-smallest disks
I also changed the pCount initialization to 0 instead of 1 as the first print only list the starting tower and is not an operation. But you may put 1 again if that if what you wanted.
PS: I tested this code and it works perfectly fine, giving 2^n-1 operations like it is supposed to.
#include <iostream>
#include <list>
const int SIZE = 12;
int pCount = 0;
using namespace std;
list<int> *lhs;
list<int> *mid;
list<int> *rhs;
void initTower(int size);
void printPeg(list<int> p);
bool printTower();
bool isEven(list<int> l);
bool move(list<int> *from, list<int> *to);
int main() {
lhs = new list<int>;
mid = new list<int>;
rhs = new list<int>;
initTower(SIZE);
printTower();
bool run = true;
bool lowest = false;
while (run) {
lowest = !lowest;
int n = SIZE;
if (n % 2 == 0) // even
{
if (lowest){
move(lhs,mid);
if (rhs->size() == SIZE) {
break;
}
move(lhs,rhs);
move(mid,rhs);
}else{
move(mid,lhs);
if (rhs->size() == SIZE) {
break;
}
move(rhs,lhs);
move(rhs,mid);
}
}else{
if (lowest){
move(lhs,rhs);
move(lhs,mid);
if (rhs->size() == SIZE) {
break;
}
move(mid,rhs);
}else{
move(rhs,lhs);
move(mid,lhs);
if (rhs->size() == SIZE) {
break;
}
move(rhs,mid);
}
}
lowest = !lowest;
}
return 0;
}
bool isEven(list<int> l) {
return l.size() % 2 == 0;
}
void initTower(int size) {
while (size--)
lhs->push_back(size + 1);
}
void printPeg(list<int> p) {
if (p.empty()) {
cout << "empty" << endl;
} else {
for (int i: p)
cout << i << " ";
cout << endl;
}
}
bool printTower() {
cout << "==============" << endl;
cout << "=====top=======" << pCount++ << endl;
printPeg(*lhs);
printPeg(*mid);
printPeg(*rhs);
cout << "==============" << endl << endl;
return true;
}
bool move(list<int> *from, list<int> *to) {
bool vailidMove = false;
int fVal = 0;
int toVal = 0;
if (!from->empty())
fVal = from->back();
if (!to->empty())
toVal = to->back();
if ((fVal < toVal || toVal == 0) && fVal > 0) {
from->pop_back();
to->push_back(fVal);
vailidMove = true;
printTower();
}else if ((fVal > toVal || fVal == 0) && (toVal > 0 && toVal != 0)) {
from->push_back(toVal);
to->pop_back();
vailidMove = true;
printTower();
}
return vailidMove;
}

C++ Infix to Postfix program, Stack is continuously empty?

I'm working on a program for a computer science class. I have everything completed and separated into the interface/implementation and for some reason, the program loops infinitely and says "Stack is empty!" after the peek() function is called.
I've tried inserting cout << statements to see if I can pinpoint the issue, however, no luck. I would appreciate it if someone else could take a look at it.
Thank You
Header
#ifndef STACK_H
#define STACK_H
/////////////////////////////////////////////////////
////Includes/////////////////////////////////////////
/////////////////////////////////////////////////////
#include <iostream>
#include <fstream>
#include <cstdlib>
#include <stdlib.h>
#include <iomanip>
#include <sstream>
#include <stdio.h>
/////////////////////////////////////////////////////
using namespace std;
/*-------------------------------------------------------------------------------------------------------------*/
template <typename Object>
class Stack
{
private:
class stackListNode
{
public:
Object data;
stackListNode *next;
private:
//Nothing to declare-->placeholder since class
//sets data members to private initially
};
stackListNode *top;
public:
/////////////////////////////////////////////////
//Constructor Function//////////////////////////
Stack() {top = NULL;}
/////////////////////////////////////////////////
//Rest of functions defined inline for simplicity
void push(char token) // Push token onto the stack and create new node for top of stack
{
stackListNode *newNode = new stackListNode;
newNode->data = token;
newNode->next = top;
top = newNode;
}
int pop()
{
if(empty())
{
cout << "Stack is empty!\n" << endl;
return NULL;
}
stackListNode *temp = top;
top = temp->next;
}
char peek()
{
if(empty())
{
cout << "Stack is empty!\n" << endl;
return NULL;
}
return top->data;
}
int empty()
{
return top == NULL;
}
};
#endif
Main File:
/////////////////////////////////////////////////////
////Includes/////////////////////////////////////////
/////////////////////////////////////////////////////
#include <iostream>
#include <fstream>
#include <string>
#include "Stack.h"
/////////////////////////////////////////////////////
using namespace std;
int precendence(char stack_beginning); //ensures order of operations.
int precendence(char*myArray);
void InFixToPostfix(ifstream& in_file);
double EvaluatePostfix(double first_operand, double second_operand, char*myArray);
int main()
{
////VARS/////////////////////////////////////////////
string absolutePath;
cout << endl;
cout << "Please type in the name of the file you would to open \n";
cin >> absolutePath;
ifstream in_file;
in_file.open(absolutePath.c_str());
if(!in_file)
{
cout << "failed to open input file\n" ;
return 1 ;
}
else
{
InFixToPostfix(in_file); //kicks off program
}
}
void InFixToPostfix(ifstream& in_file)
{
string infix;
int right_parentheses =0;
int left_parentheses =0;
while(getline(in_file, infix))
{
char myArray[infix.size()];
strcpy(myArray, infix.c_str());
for(int i = 0; i < sizeof(myArray); i++)
{
if(myArray[i] == '(')
{
right_parentheses++;
}
if(myArray[i] == ')')
{
left_parentheses++;
}
}
if(right_parentheses!=left_parentheses)
{
cout << endl;
cout << "There is a typo in one of the expressions in your file \n";
cout << "Please fix it and rerun the program \n";
exit(1);
}
for(int i = 0; i < sizeof(myArray); i++)
{
//int number = int(myArray[i]);
//deferences the pointer and reads each char in the array
//as an int rather than a character.
//int number = myArray[i];
if(isxdigit(myArray[i]) > 0) //function used to check for hexidecimal values (i.e. int's)
{
goto exit_out;
}
else if(myArray[i] == '(' || myArray[i] == ')' || myArray[i] == '+' || myArray[i] == '-' || myArray[i] == '*' || myArray[i] == '/' || myArray[i] == '\\' || myArray[i] == '\n')
{
goto exit_out;
}
else if(myArray[i] == char(32)) //checks to see if there is a space
{
goto exit_out;
}
else
{
cout << endl;
cout << "There is an invalid character in the file\n";
exit(1);
}
exit_out:;
}
////////Declares a STRING Stack////////////////////////////////
Stack<char> stack_string;
////////Declares an Int Stack/////////////////////////////////
Stack<int> stack_int;
//////////////////////////////////////////////////////////////
for(int i = 0; i < sizeof(myArray); i++)
{
int number = isxdigit(myArray[i]);
if(number > 0)
{
cout << number;
//outputs the number b/c it is an operand
}
if(myArray[i] == '(')
{
stack_string.push(myArray[i]);
}
if(myArray[i] == ')')
{
//cout << "test";
while(stack_string.peek() != '(')
{
cout << stack_string.peek();
stack_string.pop(); //pops to the peek
}
stack_string.pop(); // if there is a ), pops to the peek
}
if(myArray[i] == '+' || myArray[i] == '-' || myArray[i] == '/' || myArray[i] == '*')
{
if(stack_string.empty())
{
stack_string.push(myArray[i]); //if there's nothing on the stack, pushes the current character
//goto done;
break; //breaks out of the statement
}
char stack_beginning = stack_string.peek();
int stack_top = precendence(stack_beginning);
//int stack_top = precendence(stack_string.peek());
int operatorHierarchy = precendence(myArray);
//must be declared here because i will have been interated through array
if(operatorHierarchy > stack_top)
{
stack_string.push(myArray[i]);
}
else if(operatorHierarchy <= stack_top) //could also be an if
{
dump_out:;
cout << stack_string.peek();
stack_string.pop();
int rerunThroughStack =0;
char new_stack_beginning = stack_string.peek();
rerunThroughStack = precendence(new_stack_beginning);
if(operatorHierarchy < stack_top)
{
stack_string.push(myArray[i]);
goto done; //could break
}
if(stack_string.peek() == '(')
{
stack_string.push(myArray[i]);
goto done;
}
if(stack_string.empty())
{
stack_string.push(myArray[i]);
goto done;
}
goto dump_out;
}
}
done:;
}
cout << stack_string.peek() << endl;
//////////Evaluate Section/////////////////////////////
for(int i = 0; i < sizeof(myArray); i++)
{
if(isxdigit(myArray[i]) > 0) //this is a number
{
stack_int.push(isxdigit(myArray[i]));
goto end;
}
else if(myArray[i] == '*' || myArray[i] == '+' || myArray[i] == '-' || myArray[i] == '/')
{
double first_operand;
first_operand = stack_int.peek(); //fetches first operand on the stack_int
stack_int.pop();
//////////////////
double second_operand;
second_operand = stack_int.peek();
stack_int.pop();
//////////////////
double answer;
answer = EvaluatePostfix(first_operand, second_operand, myArray); //THIS PROBABLY IS NOT RIGHT
stack_int.push(answer);
}
end:;
}
/*
int size_of_stack;
size_of_stack = stack_int.size();
if(size_of_stack == 1)
{
cout << stack_int.peek();
}
*/
}
}
double EvaluatePostfix(double first_operand, double second_operand, char* myArray) //might have to pass array as reference
{
/*
Cycle through the characters passed in through myArray[i];
*/
for(int i = 0; i < sizeof(myArray); i++)
{
if(myArray[i] == '*')
{
double first_answer;
first_answer = (second_operand * first_operand);
return first_answer;
}
else if(myArray[i] == '/')
{
double second_answer;
second_answer = (second_operand / first_operand);
return second_answer;
}
else if(myArray[i] == '+')
{
double third_answer;
third_answer = (second_operand + first_operand);
return third_answer;
}
else if(myArray[i] == '-')
{
double fourth_answer;
fourth_answer = (second_operand - first_operand);
return fourth_answer;
}
/*
else
{
cout << "There must be an error in your file" <<endl;
break;
exit(1);
}
*/
}
}
int precendence(char stack_beginning)
{
int precendence;
if(stack_beginning == '*' || stack_beginning == '/')
{
precendence = 2;
return precendence;
}
//by making it 2, the precendence is dubbed less than +/-
if(stack_beginning == '+' || stack_beginning == '-')
{
precendence = 1;
return precendence;
}
} //by making it 1, the precendence is dubbed greater than */"/"
int precendence(char*myArray)
{
int precendence;
for(int i = 0; i < sizeof(myArray); i++)
{
if(myArray[i] == '*' || myArray[i] == '/')
{
precendence = 2;
return precendence;
}
//by making it 2, the precendence is dubbed less than +/-
if(myArray[i] == '+' || myArray[i] == '-')
{
precendence = 1;
return precendence;
}
} //by making it 1, the precendence is dubbed greater than */"/"
}