Undeclared identifier error where none seems apparent - c++

I am trying to implement a simple version of Conway's Game of Life which consists of a header file and three .cpp files (two for class functions, one for main). Here I have included my header files and two class function declaration files ( the compiler is having no problem with my Main.cpp file).
Game_Of_Life.h
#include <iostream>
#include <cstdlib>
#include <time.h>
using namespace std;
class cell{
public:
cell();
int Current_State(); // Returns state (1 or 0)
void Count_Neighbours(cell* A); // Counts the number of living cells in proximity w/o wraparound
void Set_Future(); // Determines the future value of state from # of neighbbours
void Update(); // Sets state to value of future state
void Set_Pos(unsigned int x, unsigned int y); // Sets position of cell in the array for use in counting neighbours
private:
int state;
int neighbours;
int future_state;
int pos_x;
int pos_y;
};
class cell_array{
public:
cell_array();
void Print_Array(); // Prints out the array
void Update_Array(); // Updates the entire array
void Set_Future_Array(); // Sets the value of the future array
private:
cell** A;
};
Cell_Class_Functions.cpp
#include "Game_Of_Life.h"
cell::cell(){
state = rand() % 2;
return;
}
void cell::Set_Future (){
if (state == 1){
if (neighbours < 2) future_state = 0;
else if (neighbours == 2 || neighbours == 3) future_state = 1;
else if (neighbours > 3) future_state = 0;
}
else{
if (neighbours == 3) future_state = 1;
}
return;
}
void cell::Update (){
state = future_state;
return;
}
int cell::Current_State (){
return state;
}
void cell::Set_Pos (unsigned int x, unsigned int y){
pos_x = x;
pos_y = y;
return;
}
void Count_Neighbours (cell* A){
neighbours = 0;
if (pos_x > 0) neighbours += A[pos_y * 10 + pos_x - 1].Current_State();
if (pos_x < 9) neighbours += A[pos_y * 10 + pos_x + 1].Current_State();
if (pos_y > 0) neighbours += A[(pos_y - 1) * 10 + pos_x].Current_State();
if (pos_y < 9) neighbours += A[(pos_y + 1) * 10 + pos_x].Current_State();
if (pos_x > 0 && pos_y > 0) neighbours += A[(pos_y - 1) * 10 + pos_x - 1].Current_State();
if (pos_x > 0 && pos_y < 9) neighbours += A[(pos_y + 1) * 10 + pos_x - 1].Current_State();
if (pos_x < 9 && pos_y > 0) neighbours += A[(pos_y - 1) * 10 + pos_x + 1].Current_State();
if (pos_x < 9 && pos_y < 9) neighbours += A[(pos_y + 1) * 10 + pos_x + 1].Current_State();
return;
}
Cell_Array_Class_Functions.cpp
#include "Game_Of_Life.h"
cell_array::cell_array(){
A = (cell**) malloc (sizeof(cell*)*100);
for (unsigned int r = 0; r < 10; r++){
for (unsigned int c = 0; c < 10; c++){
*A[r * 10 + c].Set_Pos(r,c);
}
}
return;
}
void cell_array::Update_Array(){
for (unsigned int r = 0; r < 10; r++){
for (unsigned int c = 0; c < 10; c++){
*A[r * 10 + c].Update();
}
}
}
void cell_array::Set_Future_Array(){
for (unsigned int r = 0; r < 10; r++){
for (unsigned int c = 0; c < 10; c++){
*A[r * 10 + c].Count_Neighbours(A);
*A[r * 10 + c].Set_Future();
}
}
return;
}
void cell_array::Print_Array(){
cout << "\n";
for (unsigned int r = 0; r < 10; r++){
for (unsigned int c = 0; c < 10; c++)cout << *A[r * 10 + c].Current_State() << " ";
cout << "\n";
}
return;
}
As far as I understand, since I included the header file with the class declarations, then I should be able to access the private members of the class through the previously declared functions in the class.
Essentially the Error Report Looks Like
Error C2065 'item' : undeclared identifier
This error appears for every private member called from the cell class.
What am I doing wrong?

Also, in your Cell_Array_Class_Functions.cpp you need to adjust your functions.
The . operator is used on objects and references.You have to deference it first to obtain a reference. That is:
(*A[r * 10 + c]).Set_Pos(r,c);
Alternatively, you can use (this is the preferred and easier to read way):
A[r * 10 + c]->Set_Pos(r,c);
The two are equivalent.

I don't see the word item anywhere in your code. However, you need to fix:
void Count_Neighbours (cell* A){ ... }
It should be:
void cell::Count_Neighbours (cell* A){ ... }

Related

Modular Connect4 game with minimax and alpha-beta pruning seg fault

I am working on makingthis connect 4 game to be modular with different grid sizes from 3x3 up to a 10x10 as well as a modular amount of winning "pucks". The program below works by passing 3 arguments which is the grid size (grid is square), the continuous amount of pucks needed to win, and who starts first (not implemented yet). So the command to run it would be connectM 6 5 1 for example.
On the code below you will see that attempt. The program works well when you use 4 as the second argument but anything above it and I am getting a segmentation fault around line 338 and I can't put my finger on it. Does anyone have any insight on something I am obviously doing wrong?
#include <stdio.h>
#include <iostream>
#include <vector>
#include <limits.h>
#include <array>
#include <sstream>
#define min(a,b) (((a) < (b)) ? (a) : (b))
#define max(a,b) (((a) > (b)) ? (a) : (b))
using namespace std;
// function declarations
void printBoard(vector<vector<int> >&);
int userMove();
void makeMove(vector<vector<int> >&, int, unsigned int);
void errorMessage(int);
int aiMove();
vector<vector<int> > copyBoard(vector<vector<int> >);
bool winningMove(vector<vector<int> >&, unsigned int);
int scoreSet(vector<unsigned int>, unsigned int);
int tabScore(vector<vector<int> >, unsigned int);
array<int, 2> miniMax(vector<vector<int> >&, unsigned int, int, int, unsigned int);
int heurFunction(unsigned int, unsigned int, unsigned int);
// Avoid magic numbers
unsigned int NUM_COL = 7; // how wide is the board
unsigned int NUM_ROW = 7; // how tall
unsigned int PLAYER = 1; // player number
unsigned int COMPUTER = 2; // AI number
unsigned int MAX_DEPTH = 5; // the default "difficulty" of the computer controlled AI
unsigned int WINNING_PUCKS = 4; //Default winning pucks
unsigned int FIRST_PLAYER = 0;
bool gameOver = false; // flag for if game is over
unsigned int turns = 0; // count for # turns
unsigned int currentPlayer = PLAYER; // current player
vector<vector<int>> board(NUM_ROW, vector<int>(NUM_COL)); // the game board
/**
* game playing function
* loops between players while they take turns
*/
void playGame() {
printBoard(board); // print initial board
while (!gameOver) { // while no game over state
if (currentPlayer == COMPUTER) { // AI move
makeMove(board, aiMove(), COMPUTER);
}
else if (currentPlayer == PLAYER) { // player move
makeMove(board, userMove(), PLAYER);
}
else if (turns == NUM_ROW * NUM_COL) { // if max number of turns reached
gameOver = true;
}
gameOver = winningMove(board, currentPlayer); // check if player won
currentPlayer = (currentPlayer == 1) ? 2 : 1; // switch player
turns++; // iterate number of turns
cout << endl;
printBoard(board); // print board after successful move
}
if (turns == NUM_ROW * NUM_COL) { // if draw condition
cout << "Draw!" << endl;
}
else { // otherwise, someone won
cout << ((currentPlayer == PLAYER) ? "AI Wins!" : "Player Wins!") << endl;
}
}
/**
* function that makes the move for the player
* #param b - the board to make move on
* #param c - column to drop piece into
* #param p - the current player
*/
void makeMove(vector<vector<int> >& b, int c, unsigned int p) {
// start from bottom of board going up
for (unsigned int r = 0; r < NUM_ROW; r++) {
if (b[r][c] == 0) { // first available spot
b[r][c] = p; // set piece
break;
}
}
}
/**
* prompts the user for their move
* and ensures valid user input
* #return the user chosen column
*/
int userMove() {
int move = -1; // temporary
while (true) { // repeat until proper input given
cout << "Enter a column: ";
cin >> move; // init move as input
if (!cin) { // if non-integer
cin.clear();
cin.ignore(INT_MAX, '\n');
errorMessage(1); // let user know
}
else if (!((unsigned int)move < NUM_COL && move >= 0)) { // if out of bounds
errorMessage(2); // let user know
}
else if (board[NUM_ROW - 1][move] != 0) { // if full column
errorMessage(3); // let user know
}
else { // if it gets here, input valid
break;
}
cout << endl << endl;
}
return move;
}
/**
* AI "think" algorithm
* uses minimax to find ideal move
* #return - the column number for best move
*/
int aiMove() {
cout << "AI is thinking about a move..." << endl;
return miniMax(board, MAX_DEPTH, 0 - INT_MAX, INT_MAX, COMPUTER)[1];
}
/**
* Minimax implementation using alpha-beta pruning
* #param b - the board to perform MM on
* #param d - the current depth
* #param alf - alpha
* #param bet - beta
* #param p - current player
*/
array<int, 2> miniMax(vector<vector<int> > &b, unsigned int d, int alf, int bet, unsigned int p) {
/**
* if we've reached minimal depth allowed by the program
* we need to stop, so force it to return current values
* since a move will never (theoretically) get this deep,
* the column doesn't matter (-1) but we're more interested
* in the score
*
* as well, we need to take into consideration how many moves
* ie when the board is full
*/
if (d == 0 || d >= (NUM_COL * NUM_ROW) - turns) {
// get current score to return
return array<int, 2>{tabScore(b, COMPUTER), -1};
}
if (p == COMPUTER) { // if AI player
array<int, 2> moveSoFar = {INT_MIN, -1}; // since maximizing, we want lowest possible value
if (winningMove(b, PLAYER)) { // if player about to win
return moveSoFar; // force it to say it's worst possible score, so it knows to avoid move
} // otherwise, business as usual
for (unsigned int c = 0; c < NUM_COL; c++) { // for each possible move
if (b[NUM_ROW - 1][c] == 0) { // but only if that column is non-full
vector<vector<int> > newBoard = copyBoard(b); // make a copy of the board
makeMove(newBoard, c, p); // try the move
int score = miniMax(newBoard, d - 1, alf, bet, PLAYER)[0]; // find move based on that new board state
if (score > moveSoFar[0]) { // if better score, replace it, and consider that best move (for now)
moveSoFar = {score, (int)c};
}
alf = max(alf, moveSoFar[0]);
if (alf >= bet) { break; } // for pruning
}
}
return moveSoFar; // return best possible move
}
else {
array<int, 2> moveSoFar = {INT_MAX, -1}; // since PLAYER is minimized, we want moves that diminish this score
if (winningMove(b, COMPUTER)) {
return moveSoFar; // if about to win, report that move as best
}
for (unsigned int c = 0; c < NUM_COL; c++) {
if (b[NUM_ROW - 1][c] == 0) {
vector<vector<int> > newBoard = copyBoard(b);
makeMove(newBoard, c, p);
int score = miniMax(newBoard, d - 1, alf, bet, COMPUTER)[0];
if (score < moveSoFar[0]) {
moveSoFar = {score, (int)c};
}
bet = min(bet, moveSoFar[0]);
if (alf >= bet) { break; }
}
}
return moveSoFar;
}
}
/**
* function to tabulate current board "value"
* #param b - the board to evaluate
* #param p - the player to check score of
* #return - the board score
*/
int tabScore(vector<vector<int> > b, unsigned int p) {
int score = 0;
vector<unsigned int> rs(NUM_COL);
vector<unsigned int> cs(NUM_ROW);
vector<unsigned int> set(WINNING_PUCKS);
/**
* horizontal checks, we're looking for sequences of WINNING_PUCKS
* containing any combination of AI, PLAYER, and empty pieces
*/
for (unsigned int r = 0; r < NUM_ROW; r++) {
for (unsigned int c = 0; c < NUM_COL; c++) {
rs[c] = b[r][c]; // this is a distinct row alone
}
for (unsigned int c = 0; c < NUM_COL - (WINNING_PUCKS - 1); c++) {
for (int i = 0; i < WINNING_PUCKS; i++) {
set[i] = rs[c + i]; // for each possible "set" of WINNING_PUCKS spots from that row
}
score += scoreSet(set, p); // find score
}
}
// vertical
for (unsigned int c = 0; c < NUM_COL; c++) {
for (unsigned int r = 0; r < NUM_ROW; r++) {
cs[r] = b[r][c];
}
for (unsigned int r = 0; r < NUM_ROW - (WINNING_PUCKS - 1); r++) {
for (int i = 0; i < WINNING_PUCKS; i++) {
set[i] = cs[r + i];
}
score += scoreSet(set, p);
}
}
// diagonals
for (unsigned int r = 0; r < NUM_ROW - (WINNING_PUCKS - 1); r++) {
for (unsigned int c = 0; c < NUM_COL; c++) {
rs[c] = b[r][c];
}
for (unsigned int c = 0; c < NUM_COL - (WINNING_PUCKS - 1); c++) {
for (int i = 0; i < WINNING_PUCKS; i++) {
set[i] = b[r + i][c + i];
}
score += scoreSet(set, p);
}
}
for (unsigned int r = 0; r < NUM_ROW - (WINNING_PUCKS - 1); r++) {
for (unsigned int c = 0; c < NUM_COL; c++) {
rs[c] = b[r][c];
}
for (unsigned int c = 0; c < NUM_COL - (WINNING_PUCKS - 1); c++) {
for (int i = 0; i < WINNING_PUCKS; i++) {
set[i] = b[r + WINNING_PUCKS - 1 - i][c + i];
}
score += scoreSet(set, p);
}
}
return score;
}
/**
* function to find the score of a set of WINNING_PUCKS spots
* #param v - the row/column to check
* #param p - the player to check against
* #return - the score of the row/column
*/
int scoreSet(vector<unsigned int> v, unsigned int p) {
unsigned int good = 0; // points in favor of p
unsigned int bad = 0; // points against p
unsigned int empty = 0; // neutral spots
for (unsigned int i = 0; i < v.size(); i++) { // just enumerate how many of each
good += (v[i] == p) ? 1 : 0;
bad += (v[i] == PLAYER || v[i] == COMPUTER) ? 1 : 0;
empty += (v[i] == 0) ? 1 : 0;
}
// bad was calculated as (bad + good), so remove good
bad -= good;
return heurFunction(good, bad, empty);
}
/**
* """heuristic function"""
* #param g - good points
* #param b - bad points
* #param z - empty spots
* #return - the score as tabulated
*/
// int heurFunction(unsigned int g, unsigned int b, unsigned int z) {
// int score = 0;
// if (g == 4) { score += 500001; } // preference to go for winning move vs. block
// else if (g == 3 && z == 1) { score += 5000; }
// else if (g == 2 && z == 2) { score += 500; }
// else if (b == 2 && z == 2) { score -= 501; } // preference to block
// else if (b == 3 && z == 1) { score -= 5001; } // preference to block
// else if (b == 4) { score -= 500000; }
// return score;
// }
int heurFunction(unsigned int g, unsigned int b, unsigned int z) {
int score = 0;
if (g == WINNING_PUCKS) { score += 500001; } // preference to go for winning move vs. block
else if (g > z) { score += 5000; }
else if (g == z) { score += 500; }
else if (b == z) { score -= 501; } // preference to block
else if (b > z) { score -= 5001; } // preference to block
else if (b == WINNING_PUCKS) { score -= 500000; }
return score;
}
/**
* function to determine if a winning move is made
* #param b - the board to check
* #param p - the player to check against
* #return - whether that player can have a winning move
*/
bool winningMove(vector<vector<int> > &b, unsigned int p) {
unsigned int winSequence = 0; // to count adjacent pieces
// for horizontal checks
for (unsigned int c = 0; c < NUM_COL - (WINNING_PUCKS - 1); c++) { // for each column
for (unsigned int r = 0; r < NUM_ROW; r++) { // each row
for (int i = 0; i < WINNING_PUCKS; i++) { // recall you need WINNING_PUCKS to win
if ((unsigned int)b[r][c + i] == p) { // if not all pieces match
winSequence++; // add sequence count
}
if (winSequence == WINNING_PUCKS) { return true; } // if WINNING_PUCKS in row
}
winSequence = 0; // reset counter
}
}
// vertical checks
for (unsigned int c = 0; c < NUM_COL; c++) {
for (unsigned int r = 0; r < NUM_ROW - (WINNING_PUCKS - 1); r++) {
for (int i = 0; i < WINNING_PUCKS; i++) {
if ((unsigned int)b[r + i][c] == p) {
winSequence++;
}
if (winSequence == WINNING_PUCKS) { return true; }
}
winSequence = 0;
}
}
// the below two are diagonal checks
for (unsigned int c = 0; c < NUM_COL - (WINNING_PUCKS - 1); c++) {
for (unsigned int r = 3; r < NUM_ROW; r++) {
for (int i = 0; i < WINNING_PUCKS; i++) {
if ((unsigned int)b[r - i][c + i] == p) {
winSequence++;
}
if (winSequence == WINNING_PUCKS) { return true; }
}
winSequence = 0;
}
}
for (unsigned int c = 0; c < NUM_COL - (WINNING_PUCKS - 1); c++) {
for (unsigned int r = 0; r < NUM_ROW - (WINNING_PUCKS - 1); r++) {
for (int i = 0; i < WINNING_PUCKS; i++) {
if ((unsigned int)b[r + i][c + i] == p) {
winSequence++;
}
if (winSequence == WINNING_PUCKS) { return true; }
}
winSequence = 0;
}
}
return false; // otherwise no winning move
}
/**
* sets up the board to be filled with empty spaces
* also used to reset the board to this state
*/
void initBoard() {
for (unsigned int r = 0; r < NUM_ROW; r++) {
for (unsigned int c = 0; c < NUM_COL; c++) {
board[r][c] = 0; // make sure board is empty initially
}
}
}
/**
* function to copy board state to another 2D vector
* ie. make a duplicate board; used for mutating copies rather
* than the original
* #param b - the board to copy
* #return - said copy
*/
vector<vector<int> > copyBoard(vector<vector<int> > b) {
vector<vector<int>> newBoard(NUM_ROW, vector<int>(NUM_COL));
for (unsigned int r = 0; r < NUM_ROW; r++) {
for (unsigned int c = 0; c < NUM_COL; c++) {
newBoard[r][c] = b[r][c]; // just straight copy
}
}
return newBoard;
}
/**
* prints the board to console out
* #param b - the board to print
*/
void printBoard(vector<vector<int> > &b) {
for (unsigned int i = 0; i < NUM_COL; i++) {
cout << " " << i;
}
cout << endl << "---------------" << endl;
for (unsigned int r = 0; r < NUM_ROW; r++) {
for (unsigned int c = 0; c < NUM_COL; c++) {
cout << "|";
switch (b[NUM_ROW - r - 1][c]) {
case 0: cout << " "; break; // no piece
case 1: cout << "O"; break; // one player's piece
case 2: cout << "X"; break; // other player's piece
}
if (c + 1 == NUM_COL) { cout << "|"; }
}
cout << endl;
}
cout << "---------------" << endl;
cout << endl;
}
/**
* handler for displaying error messages
* #param t - the type of error to display
*/
void errorMessage(int t) {
if (t == 1) { // non-int input
cout << "Use a value 0.." << NUM_COL - 1 << endl;
}
else if (t == 2) { // out of bounds
cout << "That is not a valid column." << endl;
}
else if (t == 3) { // full column
cout << "That column is full." << endl;
}
cout << endl;
}
/**
* main driver
*/
int main(int argc, char** argv) {
// int i = -1; bool flag = false;
// if (argc == 2) {
// istringstream in(argv[1]);
// if (!(in >> i)) { flag = true; }
// if (i > (int)(NUM_ROW * NUM_COL) || i <= -1) { flag = true; }
// if (flag) { cout << "Invalid command line argument, using default depth = 5." << endl; }
// else { MAX_DEPTH = i; }
// }
if(argc <= 1){
cout << "No arguments fed. Terminating";
return 0;
}
if(argc == 4){
int gridSize = atoi(argv[1]);
int diskAmount = atoi(argv[2]);
bool firstTurn = (bool)argv[3];
if(gridSize < 3 || gridSize > 10){
cout << "Incorrect Grid size";
return 0;
}
if(diskAmount < 1 || diskAmount > gridSize){
cout << "Incorrect disk amount";
return 0;
}
NUM_COL = gridSize;
NUM_ROW = gridSize;
WINNING_PUCKS = diskAmount;
FIRST_PLAYER = firstTurn;
}
else{
cout << "Incorrect amount of arguments. Terminating";
return 0;
}
//cout << NUM_COL << endl << WINNING_PUCKS << endl << FIRST_PLAYER << endl;
initBoard(); // initial setup
playGame(); // begin the game
return 0; // exit state
}
It looks to me that you didn't change one of the hard-coded values from your earlier version of the game. On line 336, you have
for (unsigned int r = 3; r < NUM_ROW; r++) {
This is only correct when WINNING_PUCKS is set to 4. The general case should be:
for (unsigned int r = (WINNING_PUCKS - 1); r < NUM_ROW; r++) {
Note that while this part should now work correctly, when I ran it, it still crashes when an end-game is reached with the error message:
double free or corruption (out)
Aborted (core dumped)
I haven't determined what caused this yet.

Data Management Error C++

I am having difficulties with my code. The issue is that even though my program runs all the way through, it still crashes at the end. My IDE gives me no disapproval and there is no indicator as to why my program is failing right at the end, so I am led to believe there is something going out of bounds or something messing up my stack. I have looked through my code and nothing appears to be out of bounds, so I am entirely confused on this matter.
I am using a header file I created, a file to contain my functions from the header file, and a main method file. The error is a result of the file containing my functions.
The fields of my class are
size - int
low - int
high - int
windowSize - int
*filteredArray - int
array[] - int
Here is the header file:
#ifndef FILTER_HPP_
#define FILTER_HPP_
#include<iostream>
class Filter {
int size;
int high;
int low;
int windowSize;
int *filteredArray;
int array[];
public:
// Constructor
Filter(int windowSize);
// Methods
void randArrayGen();
int* randArrayGenRecurHelper(int arrayRecur[], int count);
void randArrayGenRecur();
void printArrays();
int hanning(int ar[]);
void hanningFilter();
void graphicArrays();
int getSize();
int getHigh();
int getLow();
};
#endif /* FILTER_HPP_ */
Here is the code:
#include "Filter.hpp"
#include <iostream>
#include <time.h>
#include <stdlib.h>
#include <cmath>
#include <array>
#include <string>
#include <cstring>
using namespace std;
// Constructor
Filter::Filter(int num){
size = ((rand() % 25) + 25);
high = ((rand() % 6) + 5);
low = ((rand() % 6) + 5) * -1;
windowSize = num;
randArrayGen();
hanningFilter();
}
void Filter::randArrayGen(){
for(int i = 0; i < size;i++){
array[i] = (rand() % (high + low * -1)) + low;
}
}
int Filter::hanning(int ar[]){
int weightAvg;
if(windowSize == 3){
weightAvg = (ar[0] + ar[1] * 2 +ar[2]) / 4;
}
else if(windowSize == 5){
weightAvg = (ar[0] + ar[1] * 2 + ar[2] * 3 + ar[3] * 2 + ar[4]) / 9;
}
else if(windowSize == 7){
weightAvg = (ar[0] + ar[1] * 2 + ar[2] * 3 + ar[3] * 4 + ar[4] *3 + ar[5] * 2 + ar[6]) / 16;
}
else if(windowSize == 9){
weightAvg = (ar[0] + ar[1] * 2 +ar[2] * 3 + ar[3] * 4 + ar[4] * 5 + ar[5] * 4 + ar[6] * 3 + ar[7] * 2 + ar[8]) / 25;
}
else{
weightAvg = 0;
}
return weightAvg;
}
void Filter::hanningFilter(){
filteredArray = new int[size];
for(int i = 0; i < size; i++){
if(i - (windowSize/2) < 0 or i + (windowSize/2) > size - 1){
filteredArray[i] = 0;
}
else{
filteredArray[i] = hanning(&array[i-(windowSize/2)]);
}
}
}
int Filter::getHigh(){
return high;
}
int Filter::getLow(){
return low;
}
int Filter::getSize(){
return size;
}
You don't allocate memory for your array:
int array[];
And when you index it like:
for(int i = 0; i < size;i++){
array[i] = (rand() % (high + low * -1)) + low;
}
you invoke Undefined Behavior, since you go out of bounds (you request the first element for example, but from an array of unknown size).
You could declare the array with a fixed size, like this for example:
int array[100];
However, since this is C++, consider using std::vector. An immediate advantage is that you don't have to hardcode a size for your statically allocated array, but you can rely on the vector's ability to resize as the data are inserted/pushed into it.

Runtime Error signal 11 on simple C++ code

I am getting a runtime error with this code and I have no idea why.
I am creating a grid and then running a BFS over it. The objective here is to read in the rows and columns of the grid, then determine the maximum number of stars you can pass over before reaching the end.
The start is the top left corner and the end is the bottom right corner.
You can only move down and right. Any ideas?
#include <iostream>
#include <queue>
using namespace std;
int main() {
int r, c, stars[1001][1001], grid[1001][1001], ns[1001][1001];
pair<int, int> cr, nx;
char tmp;
queue<pair<int, int> > q;
cin >> r >> c;
for(int i = 0; i < r; i++) {
for(int j = 0; j < c; j++) {
cin >> tmp;
if(tmp == '.') {
grid[i][j] = 1000000000;
ns[i][j] = 0;
stars[i][j] = 0;
}
else if(tmp == '*') {
grid[i][j] = 1000000000;
ns[i][j] = 1;
stars[i][j] = 1;
}
else
grid[i][j] = -1;
}
}
grid[0][0] = 0;
cr.first = 0;
cr.second = 0;
q.push(cr);
while(!q.empty()) {
cr = q.front();
q.pop();
if(cr.first < r - 1 && grid[cr.first + 1][cr.second] != -1 && ns[cr.first][cr.second] + stars[cr.first + 1][cr.second] > ns[cr.first + 1][cr.second]) {
nx.first = cr.first + 1; nx.second = cr.second;
grid[nx.first][nx.second] = grid[cr.first][cr.second] + 1;
ns[nx.first][nx.second] = ns[cr.first][cr.second] + stars[cr.first + 1][cr.second];
q.push(nx);
}
if(cr.second < c - 1 && grid[cr.first][cr.second + 1] != -1 && ns[cr.first][cr.second] + stars[cr.first][cr.second + 1] > ns[cr.first][cr.second + 1]) {
nx.first = cr.first; nx.second = cr.second + 1;
grid[nx.first][nx.second] = grid[cr.first][cr.second] + 1;
ns[nx.first][nx.second] = ns[cr.first][cr.second] + stars[cr.first][cr.second + 1];
q.push(nx);
}
}
if(grid[r - 1][c - 1] == 1000000000)
cout << "Impossible" << endl;
else
cout << ns[r - 1][c - 1] << endl;
}
Sample input :
6 7
.#*..#.
..*#...
#.....#
..###..
..##..*
*#.....
I'm guessing your stack is not big enough for
int stars[1001][1001], grid[1001][1001], ns[1001][1001];
which is 3 * 1001 * 1001 * sizeof(int) bytes. That's ~12MB if the size of int is 4 bytes.
Either increase the stack size with a compiler option, or go with dynamic allocation i.e. std::vector.
To avoid the large stack you should allocate on the heap
Since you seem to have three parallel 2 - dimension arrays you could
maybe create struct that contains all three values for a x,y position.
That would make it easier to maintain:
struct Area
{
int grid;
int ns;
int stars;
};
std::vector<std::array<Area,1001>> dim2(1001);
dim2[x][y].grid = 100001;
...

class variable access within recursive function

for an intro program, we were asked to build a program that could find every single possible working magic square of a given size. I am having trouble modifying a class variable from within a recursive function. I am trying to increment the number of magic squares found every time the combination of numbers I am trying yields a magic square.
More specifically, I am trying to modify numSquares within the function recursiveMagic(). After setting a breakpoint at that specific line, the variable, numSquares does not change, even though I am incrementing it. I think it has something to do with the recursion, however, I am not sure. If you want to lend some advice, I appreciate it.
//============================================================================
// Name : magicSquare.cpp
// Author :
// Version :
// Copyright : Your copyright notice
// Description : Hello World in C++, Ansi-style
//============================================================================
#include <iostream>
using namespace std;
/**
* MagicSquare
*/
class MagicSquare {
private:
int magicSquare[9];
int usedNumbers[9];
int numSquares;
int N;
int magicInt;
public:
MagicSquare() {
numSquares = 0;
for (int i = 0; i < 9; i++)
usedNumbers[i] = 0;
N = 3; //default is 3
magicInt = N * (N * N + 1) / 2;
}
MagicSquare(int n) {
numSquares = 0;
for (int i = 0; i < 9; i++)
usedNumbers[i] = 0;
N = n;
magicInt = N * (N * N + 1) / 2;
}
void recursiveMagic(int n) {
for (int i = 1; i <= N * N + 1; i++) {
if (usedNumbers[i - 1] == 0) {
usedNumbers[i - 1] = 1;
magicSquare[n] = i;
if (n < N * N)
recursiveMagic(n + 1);
else {
if (isMagicSquare()) {
numSquares++; //this is the line that is not working correctly
printSquare();
}
}
usedNumbers[i - 1] = 0;
}
}
}
//To efficiently check all rows and collumns, we must convert the one dimensional array into a 2d array
//since the sudo 2d array looks like this:
// 0 1 2
// 3 4 5
// 6 7 8
//the following for-if loops convert the i to the appropriate location.
bool isMagicSquare() {
for (int i = 0; i < 3; i++) {
if ((magicSquare[i * 3] + magicSquare[i * 3 + 1] + magicSquare[i * 3 + 2]) != magicInt) //check horizontal
return false;
else if ((magicSquare[i] + magicSquare[i + 3] + magicSquare[i + 6]) != magicInt) // check vertical
return false;
}
if ((magicSquare[0] + magicSquare[4] + magicSquare[8]) != magicInt)
return false;
if ((magicSquare[6] + magicSquare[4] + magicSquare[2]) != magicInt)
return false;
return true;
}
/**
* printSquare: prints the current magic square combination
*/
void printSquare() {
for (int i = 0; i < 3; i++)
cout << magicSquare[i * 3] << " " << magicSquare[i * 3 + 1]
<< " " << magicSquare[i * 3 + 2] << endl;
cout << "------------------" << endl;
}
/**
* checkRow: checks to see if the current row will complete the magic square
* #param i - used to determine what row is being analyzed
* #return true if it is a working row, and false if it is not
*/
bool checkRow(int i) {
i = (i + 1) % 3 - 1;
return (magicSquare[i * 3] + magicSquare[i * 3 + 1] + magicSquare[i * 3 + 2]) == magicInt;
}
int getnumSquares() {
return numSquares;
}
}; //------End of MagicSquare Class-----
int main() {
MagicSquare square;
cout << "Begin Magic Square recursion:" << endl << "------------------"
<< endl;
square.recursiveMagic(0);
cout << "Done with routine, returned combinations: " << square.getnumSquares() << endl;
return 0;
}
The array is being overwritten leading to overwriting the numSquares field.
class MagicSquare {
private:
int magicSquare[9];
int usedNumbers[9];
Changes to
class MagicSquare {
private:
int magicSquare[10];
int usedNumbers[10];
Also in your initializer the loop says < 9 but what you want to say is < 10. Or just use memset is better for that purpose.

Laguerre interpolation algorithm, something's wrong with my implementation

This is a problem I have been struggling for a week, coming back just to give up after wasted hours...
I am supposed to find coefficents for the following Laguerre polynomial:
P0(x) = 1
P1(x) = 1 - x
Pn(x) = ((2n - 1 - x) / n) * P(n-1) - ((n - 1) / n) * P(n-2)
I believe there is an error in my implementation, because for some reason the coefficents I get seem way too big. This is the output this program generates:
a1 = -190.234
a2 = -295.833
a3 = 378.283
a4 = -939.537
a5 = 774.861
a6 = -400.612
Description of code (given below):
If you scroll the code down a little to the part where I declare array, you'll find given x's and y's.
The function polynomial just fills an array with values of said polynomial for certain x. It's a recursive function. I believe it works well, because I have checked the output values.
The gauss function finds coefficents by performing Gaussian elimination on output array. I think this is where the problems begin. I am wondering, if there's a mistake in this code or perhaps my method of veryfying results is bad? I am trying to verify them like that:
-190.234 * 1.5 ^ 5 - 295.833 * 1.5 ^ 4 ... - 400.612 = -3017,817625 =/= 2
Code:
#include "stdafx.h"
#include <conio.h>
#include <iostream>
#include <iomanip>
#include <math.h>
using namespace std;
double polynomial(int i, int j, double **tab)
{
double n = i;
double **array = tab;
double x = array[j][0];
if (i == 0) {
return 1;
} else if (i == 1) {
return 1 - x;
} else {
double minusone = polynomial(i - 1, j, array);
double minustwo = polynomial(i - 2, j, array);
double result = (((2.0 * n) - 1 - x) / n) * minusone - ((n - 1.0) / n) * minustwo;
return result;
}
}
int gauss(int n, double tab[6][7], double results[7])
{
double multiplier, divider;
for (int m = 0; m <= n; m++)
{
for (int i = m + 1; i <= n; i++)
{
multiplier = tab[i][m];
divider = tab[m][m];
if (divider == 0) {
return 1;
}
for (int j = m; j <= n; j++)
{
if (i == n) {
break;
}
tab[i][j] = (tab[m][j] * multiplier / divider) - tab[i][j];
}
for (int j = m; j <= n; j++) {
tab[i - 1][j] = tab[i - 1][j] / divider;
}
}
}
double s = 0;
results[n - 1] = tab[n - 1][n];
int y = 0;
for (int i = n-2; i >= 0; i--)
{
s = 0;
y++;
for (int x = 0; x < n; x++)
{
s = s + (tab[i][n - 1 - x] * results[n-(x + 1)]);
if (y == x + 1) {
break;
}
}
results[i] = tab[i][n] - s;
}
}
int _tmain(int argc, _TCHAR* argv[])
{
int num;
double **array;
array = new double*[5];
for (int i = 0; i <= 5; i++)
{
array[i] = new double[2];
}
//i 0 1 2 3 4 5
array[0][0] = 1.5; //xi 1.5 2 2.5 3.5 3.8 4.1
array[0][1] = 2; //yi 2 5 -1 0.5 3 7
array[1][0] = 2;
array[1][1] = 5;
array[2][0] = 2.5;
array[2][1] = -1;
array[3][0] = 3.5;
array[3][1] = 0.5;
array[4][0] = 3.8;
array[4][1] = 3;
array[5][0] = 4.1;
array[5][1] = 7;
double W[6][7]; //n + 1
for (int i = 0; i <= 5; i++)
{
for (int j = 0; j <= 5; j++)
{
W[i][j] = polynomial(j, i, array);
}
W[i][6] = array[i][1];
}
for (int i = 0; i <= 5; i++)
{
for (int j = 0; j <= 6; j++)
{
cout << W[i][j] << "\t";
}
cout << endl;
}
double results[6];
gauss(6, W, results);
for (int i = 0; i < 6; i++) {
cout << "a" << i + 1 << " = " << results[i] << endl;
}
_getch();
return 0;
}
I believe your interpretation of the recursive polynomial generation either needs revising or is a bit too clever for me.
given P[0][5] = {1,0,0,0,0,...}; P[1][5]={1,-1,0,0,0,...};
then P[2] is a*P[0] + convolution(P[1], { c, d });
where a = -((n - 1) / n)
c = (2n - 1)/n and d= - 1/n
This can be generalized: P[n] == a*P[n-2] + conv(P[n-1], { c,d });
In every step there is involved a polynomial multiplication with (c + d*x), which increases the degree by one (just by one...) and adding to P[n-1] multiplied with a scalar a.
Then most likely the interpolation factor x is in range [0..1].
(convolution means, that you should implement polynomial multiplication, which luckily is easy...)
[a,b,c,d]
* [e,f]
------------------
af,bf,cf,df +
ae,be,ce,de, 0 +
--------------------------
(= coefficients of the final polynomial)
The definition of P1(x) = x - 1 is not implemented as stated. You have 1 - x in the computation.
I did not look any further.