class variable access within recursive function - c++

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.

Related

Heap Corruption detected: after Normal block(#176)

So I got this introduction to Programming assignment, I have to write a program that find the nth member of the following sequence 1, 121, 1213121, 121312141213121.. and so on. Basically, the first member is 1, and every next one is made of [the previous member] [n] [the previous member]. N < 10. So I got this problem that I do not understand, tried searching for it in the internet but didn't get anything that can help me.
#include "stdafx.h"
#include <iostream>
using namespace std;
int size(int n, int realsize);
int main()
{
int n;
cin >> n;
if (n == 1) {
cout << "1";
return 0;
}
int helper = 0;
char c = '2';
char* look;
char* say;
say = new char[size(n, 1) + 1]();
look = new char[size(n - 1, 1) + 1]();
look[0] = '1';
while (helper < n) {
for (int i = 0; i < size(helper + 1, 1); i++) {
say[i] = look[i];
}
say[size(helper + 1, 1)] = c;
for (int i = size(helper + 1, 1) + 1; i < size(helper + 1, 1) * 2 + 1; i++) {
say[i] = look[i - (size(helper + 1, 1) + 1)];
}
for (int i = 0; i < size(helper + 1, 1) * 2 + 1; i++) {
look[i] = say[i];
}
helper += 1;
}
cout << say;
delete[] say;
delete[] look;
return 0;
}
int size(int n, int realsize)
{
if (n == 1)
return realsize;
else
return size(n - 1, realsize * 2 + 1);
}
You are overwriting the capacity of your look variable. It ends out being written with the entire contents of say, so it needs to have that same size as well.
While I don't condone the below code as good code, it has minimal adjustments from your own implementation and should give a more solid base to continue towards a working outcome. I tested it with the first couple of numbers, but that's no guarantee it is perfect.
#include <iostream>
using namespace std;
int size(int n, int realsize);
int main()
{
int n;
cin >> n;
if (n == 1)
{
cout << "1";
return 0;
}
int helper = 0;
char c = '2';
char * look;
char * say;
say = new char[size(n, 1) + 1]; // Ditch the () call, which is confusing.
look = new char[size(n, 1) + 1]; // Make the same size as "say"
look[0] = '1';
while (helper < n - 1) // You're overrunning this loop I think, so I did it to n - 1.
{
for (int i = 0; i < size(helper + 1, 1); i++)
{
say[i] = look[i];
}
say[size(helper + 1, 1)] = c + helper; // You were adding '2' every time, so this will add 2, 3, 4, etc incrementally.
for (int i = size(helper + 1, 1) + 1; i < size(helper + 1, 1) * 2 + 1; i++)
{
say[i] = look[i - (size(helper + 1, 1) + 1)];
}
for (int i = 0; i < size(helper + 1, 1) * 2 + 1; i++)
{
look[i] = say[i];
}
helper += 1;
}
say[size(n, 1)] = '\0'; // Null-terminate "say" before printing it out.
cout << say;
delete[] say;
delete[] look;
return 0;
}
int size(int n, int realsize)
{
if (n == 1)
return realsize;
else
return size(n - 1, realsize * 2 + 1);
}

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;
...

Undeclared identifier error where none seems apparent

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){ ... }

Cplex c++ multidimensional decision variable

I'm new using cplex and I try to find some information on internet but didn't find clear stuff to help me in my problem.
I have P[k] k will be equal to 1 to 4
and I have a decision variable x[i][k] must be equal to 0 or 1 (also p[k])
the i is between 1 to 5
For now I do like this
IloEnv env;
IloModel model(env);
IloNumVarArray p(env);
p.add(IloNumVar(env, 0, 1));
p.add(IloNumVar(env, 0, 1));
p.add(IloNumVar(env, 0, 1));
IloIntVar x(env, 0, 1);
model.add(IloMaximize(env, 1000 * p[1] + 2000 * p[2] + 500 * p[3] + 1500 * p[4]));
for(int k = 1; k <= 4; k++){
for(int i = 1; i <= 5; i++){
model.add(x[i][k] + x[i][k] + x[i][k] + x[i][k] + x[i][k] => 2 * p[k]; );
}}
The loop should do something like this:
x[1][1] + x[2][1] + x[3][1] + x[4][1] + x[5][1] => 2 * p[1];
x[1][2] + x[2][2] + x[3][2] + x[4][2] + x[5][2] => 2 * p[2];
x[1][3] + x[2][3] + x[3][3] + x[4][3] + x[5][3] => 2 * p[3];
x[1][4] + x[2][4] + x[3][4] + x[4][4] + x[5][4] => 3 * p[4];
but I'm far away from this result.
Does anyone have an idea?
Thanks
You probably want to use an IloNumExpr
for(int k = 0; k < 4; k++){
IloNumExpr sum_over_i(env);
for(int i = 0; i < 5; i++){
sum_over_i += x[i][k];
}
model.add(sum_over_i >= 2 * p[k]; );
}
You also need to declare x as a 2-dimensional array.
IloArray x(env, 4);
for (int k = 0; k < 4; ++k)
x[k] = IloIntVarArray(env, 5, 0, 1);
Also, in c++, array indices are from 0 to size-1, not 1 to size. Your objective should be written
model.add(IloMaximize(env, 1000 * p[0] + 2000 * p[1] + 500 * p[2] + 1500 * p[3]));
Usertfwr already gave a good answer, but I would like to give another version of solution which might help you to code CPLEX applications in a more generic way. First, I would suggest you to use a text file to hold all the data (objective function coefficients) which will be fed into the program. In your case, you only have to copy literally the following matrix like data to notepad and name it as “coef.dat”:
[1000, 2000, 500, 1500]
Now comes the full code, let me know if have difficulties understanding any statement:
#include <ilcplex/ilocplex.h>
#include <fstream>
#include <iostream>
ILOSTLBEGIN
int main(int argc, char **argv) {
IloEnv env;
try {
const char* inputData = "coef.dat";
ifstream inFile(inputData); // put your data in the same directory as your executable
if(!inFile) {
cerr << "Cannot open the file " << inputData << " successfully! " <<endl;
throw(-1);
}
// Define parameters (coef of objective function)
IloNumArray a(env);
// Read in data
inFile >> a;
// Define variables
IloBoolVarArray p(env, a.getSize()); // note that a.getSize() = 4
IloArray<IloBoolVarArray> X(env, 5); // note that you need a 5x4 X variables, not 4x5
for(int i = 0; i < 5; i++) {
X[i] = IloBoolVarArray(env,4);
}
// Build model
IloModel model(env);
// Add objective function
IloExpr objFun (env);
for(int i = 0; i < a.getSize(); i++){
objFun += a[i]*p[i];
}
model.add(IloMaximize(env, objFun));
objFun.end();
// Add constraints -- similar to usertfwr’s answer
for(int i = 0; i < 4; k++){
IloExpr sumConst (env);
for(int j = 0; j < 5; i++){
sumConst += x[j][i];
}
// before clearing sumConst expr, add it to model
model.add(sumConst >= 2*p[i]);
sumConst.end(); // very important to end after having been added to the model
}
// Extract the model to CPLEX
IloCplex cplex(mod);
// Export the LP model to a txt file to check correctness
//cplex.exportModel("model.lp");
// Solve model
cplex.solve();
}
catch (IloException& e) {
cerr << "Concert exception caught: " << e << endl;
}
catch (...) {
cerr << "Unknown exception caught" << endl;
}
env.end();
}

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.