What is corrupting the stack of this multidimensional array? - c++

This script produces a fibonacci spiral which starts off in the centre and branches outward. Although the output is correct, i get an error message saying:
"Run-Time Check Failure #2 - Stack around the variable 'fibArr' was corrupted."
I've tried reducing fibCount by 1, but this caused the central number to be 0 which I dont want.
int fibFunc(int);
int main() {
//--setting variables
const int rowCount = 5, colCount = 5;
const int fibCount = rowCount * colCount - 1;
static int f;
int i, j;
//--creating grid
int grid[rowCount][colCount] = { 0 };
//Create fibArr
f = fibCount;
int fibArr[fibCount];
while (f >= 0) {
fibArr[f] = fibFunc(f);
f--;
}
//directions settings
enum direction {
DOWN, RIGHT, UP, LEFT
} d = DOWN;
//spiral loop
int R = 0, C = 0; //R for row, C for column
f = fibCount;
while (f >= 0) {
grid[R][C] = fibArr[f];
f--;
if (d == DOWN) {
if (grid[R+1][C] == 0)
R++;
else d = RIGHT;
}
if (d == RIGHT) {
if (grid[R][C+1] == 0)
C++;
else d = UP;
}
if (d == UP) {
if (grid[R-1][C] == 0)
R--;
else d = LEFT;
}
if (d == LEFT) {
if (grid[R][C-1] == 0)
C--;
else {
d = DOWN;
R++;
}
}
}
printFib(fibArr, fibCount);
for (i = 0; i < rowCount; i++) {
for (j = 0; j < colCount; j++) {
cout << setw(7) << grid[i][j];
}
cout << endl;
cout << endl;
}
system("pause>nul");
}
int fibFunc(int n) {
if (n == 0 || n == 1)
return 1;
else
return fibFunc(n - 1) + fibFunc(n - 2);
}
Output
75025 55 89 144 233
46368 34 1 2 377
28657 21 1 3 610
17711 13 8 5 987
10946 6765 4181 2584 1597

As juanchopanza pointed out, array indexing is from 0 to size - 1.
const int rowCount = 5, colCount = 5;
const int fibCount = rowCount * colCount - 1;
This would result in:
fibCount = 24 = ( 5 * 5 ) - 1;
Further down, at your while loop:
int R = 0, C = 0; //R for row, C for column
f = fibCount;
while (f >= 0) {
grid[R][C] = fibArr[f]; // f = 24; size = 24;
...
}
Here you take a value from your array fibArray with the index of 24. Last index would be 23.
Change this to:
const int fibCount = rowCount * colCount;
Then before your while loop:
f = fibCount - 1;
Besides that I would use a single dimensional array like this:
int rows = 5, cols = 5;
char* tst = new char[ rows * cols ];
int select_row = 2;
int select_col = 3;
tst[ select_row * cols + select_col ] = 65;
char c = tst[ select_row * cols + select_col ];
delete[] tst;

Related

Matrix with elements different from zero only on the main diagonal and antidiagonal c++

I have a matrix like this:
1 0 0 2
0 1 2 0
0 5 3 0
1 0 0 2
I store them in a
vector<int>v
From
v[0][0] - v[n][n] + v[0][n] - v[n][0]
Here is how i try to read the matrix
ostream& operator<<(ostream& s, const Xmatrix& a)
{
unsigned int matrixSize;
s >> matrixSize;
a.reSize(matrixSize);
int x = 0;
for(unsigned int i = 0; i < matrixSize; ++i) {
s >> a(i,i);
}
for(unsigned int i = matrixSize - 1; i > matrixSize + 1; --i) {
if(x == matrixSize / 2){
x = x + 2;
s >> a(x,i);
}
else{
s >> a(x,i);
x++;
}
}
return s;
}
And here is how i try to do the multiplication
Xmatrix operator*(const Xmatrix& a ,const Xmatrix& b)
{
if(a._v.size() != b._v.size()){
throw Xmatrix::DIFFERENT;
}
Xmatrix c(a._v.size());
int x = a._v.size();
int m = x/2;
for(unsigned int i = 0; i < c._v.size(); ++i){
//c._v[i] = a._v[i] * b._v[i];
c._v[i] = a._v[i] * b._v[i] + a._v[i] * b._v[x+i] + a._v[m] * b._v[x+i] + a._v[m] * b._v[i];
x--;
m++;
}
return c;
}
For some reason it doesn't work,it gives really stupid numbers
Did i store the elements and did the calc right?
I did this with classes

Sparse matrix compressed on rows in C++

I have to implement the CSR matrix data structure in C++ using 3 dynamic arrays (indexing starts at 0) and I've got stuck. So I have to implement 2 functions:
1) modify(int i, int j, TElem e) - modifies the value of (i,j) to e or adds if (if it does not exist) or deletes it if e is null.
2) element(int i, int j) const - returns the value found on (i,j)
I wanted to test my code in the next way:
Matrix m(4,4); m.print(); It will print:
Lines: 0 0 0 0 0
Columns:
Values:
(And this is fine)
Now if I want to modify: m.modify(1,1,5); //The element (1,1) will be set to 5
The output of m.print(); will be:
Lines: 0 1 1 1 1
Columns: 1
Values: 5 (which again is fine)
And now if I want to print m.element(1, 1) it will return 0 and m.element(0, 1) will return 5.
This is my implementation of element(int i, int j) :
int currCol;
for (int pos = this->lines[i]; pos < this->lines[i+1]; pos++) {
currCol = this->columns[pos];
if (currCol == j)
return this->values[pos];
else if (currCol > j)
break;
}
return NULL_TELEM;
The constructor looks like this:
Matrix::Matrix(int nrLines, int nrCols) {
if (nrLines <= 0 || nrCols <= 0)
throw exception();
this->nr_lines = nrLines;
this->nr_columns = nrCols;
this->values = new TElem[100];
this->values_capacity = 1;
this->values_size = 0;
this->lines = new int[nrLines + 1];
this->columns = new TElem[100];
this->columns_capacity = 1;
this->columns_size = 0;
for (int i = 0; i <= nrLines; i++)
this->lines[i] = NULL_TELEM;
}
This is the "modify" method:
TElem Matrix::modify(int i, int j, TElem e) {
if (i < 0 || j < 0 || i >= this->nr_lines || j >= nr_columns)
throw exception();
int pos = this->lines[i];
int currCol = 0;
for (; pos < this->lines[i + 1]; i++) {
currCol = this->columns[pos];
if (currCol >= j)
break;
}
if (currCol != j) {
if (!(e == 0))
add(pos, i, j, e);
}
else if (e == 0)
remove(pos, i);
else
this->values[pos] = e;
return NULL_TELEM;
}
And this is the inserting method:
void Matrix::add(int index, int line, int column, TElem value)
{
this->columns_size++;
this->values_size++;
for (int i = this->columns_size; i >= index + 1; i--) {
this->columns[i] = this->columns[i - 1];
this->values[i] = this->values[i - 1];
}
this->columns[index] = column;
this->values[index] = value;
for (int i = line; i <= this->nr_lines; i++) //changed to i = line + 1;
this->lines[i]++;
}
Can somebody help me, please? I can't figure out why this happens and I really need to finish this implementation these days.
It just can't pass the next test. And if I want to print the elements i have (4,0)=0 (4,1)=0 ... (4,8)=0 and (4,9)=3. Now this looks pretty weird why it happens.
void testModify() {
cout << "Test modify" << endl;
Matrix m(10, 10);
for (int j = 0; j < m.nrColumns(); j++)
m.modify(4, j, 3);
for (int i = 0; i < m.nrLines(); i++)
for (int j = 0; j < m.nrColumns(); j++)
if (i == 4)
assert(m.element(i, j) == 3);
//cout << i << " " << j << ":" << m.element(i, j)<<'\n';
else
assert(m.element(i, j) == NULL_TELEM);
}
When you call modify(1, 1, 5) with an empty matrix (all zeros), that results in a call to add(0, 1, 1, 5). That increments columns_size and values_size (both to 1), the for loop body will not execute, you update columns[0] to 1 and values[0] to 5, then increment all the lines values starting at element lines[1], setting them all to 1 (lines[0] will still be 0). But lines[1] should indicate the element we just added, so it should be 0, since the value is found using columns[0].
The for loop at the end of add should start at element line + 1.

Program crashes - Division by zero

My code goes like this:
if (x[b] != x[c] && x[a] != x[b])
{
if(x[a] != x[b] != x[c] != x[d])
{
if(y[a] != y[b] != y[c] != y[d])
{
int m = (y[a] - y[b])/(x[a] - x[b]);
int b = y[a] - x[a] * m;
if((y[c] - x[c]*m > b && y[d] - x[d]*m > b)|| (y[c] - x[c]*m < b && y[d] - x[d]*m < b)){
m = (y[b] - y[c])/(x[b] - x[c]);
b = y[b] - x[b] * m;
if((y[a] - x[a]*m > b && y[d] - x[d]*m > b)|| (y[a] - x[a]*m < b && y[d] - x[d]*m < b))
{
int xx[4];
int yy[4];
xx[0] = x[a];
xx[1] = x[b];
xx[2] = x[c];
xx[3] = x[d];
yy[0] = y[a];
yy[1] = y[b];
yy[2] = y[c];
yy[3] = y[d];
if(c == 1)
{
c = 0;
pt = povrsina(xx, yy);
pc = p - pt;
}
pv = povrsina(xx, yy);
pr = p - pv;
if(pr < pc)
{
pc = pr;
pt = pv;
}
else if(pr == pc)
{
pt = max(pt, pv);
}
}
}
}
}
}
The input I have tried is this:
5
30
0 0
10 0
0 10
10 10
7 3
My program crashes with an error code for Division by zero in line 174:
m = (y[b] - y[c])/(x[b] - x[c]);
So I added the first if statement checking
if x[b] != x[c]
but it still crashes for some reason with the same error code and in the same line.
The following works correctly.
int n = 0;
double p = 0;
scanf("%d\n%lf", &n, &p);
int *x = (int *) malloc(sizeof(int) * n);
int *y = (int *) malloc(sizeof(int) * n);
for(int i = 0; i < n; i++){
scanf("%d %d", &x[i], &y[i]);
}
for(int i = 0; i < n; i++){
printf("%d %d\n", x[i], y[i]);
}
See the demo.
Update
Your code is crashing because of the following line.
int m = (y[a] - y[b])/(x[a] - x[b]);
Think if the value of a, b, c, d is 0, 2, 3, 4, then the denominator term (x[a] - x[b]) represents (x[0] - x[2]) which is equal to zero, right? Because the 1st and 3rd input is 0 0 and 0 10.
If you divide a value by zero, then it becomes infinity and your program will crash at that time. While writing statement with division operation, make sure the divisor is not zero.

C++ Not Counting white beands

I need some help. I'm writing a code in C++ that will ultimately take a random string passed in, and it will do a break at every point in the string, and it will count the number of colors to the right and left of the break (r, b, and w). Here's the catch, the w can be either r or b when it breaks or when the strong passes it ultimately making it a hybrid. My problem is when the break is implemented and there is a w immediately to the left or right I can't get the program to go find the fist b or r. Can anyone help me?
#include <stdio.h>
#include "P2Library.h"
void doubleNecklace(char neck[], char doubleNeck[], int size);
int findMaxBeads(char neck2[], int size);
#define SIZE 7
void main(void)
{
char necklace[SIZE];
char necklace2[2 * SIZE];
int brk;
int maxBeads;
int leftI, rightI, leftCount = 0, rightCount=0, totalCount, maxCount = 0;
char leftColor, rightColor;
initNecklace(necklace, SIZE);
doubleNecklace(necklace, necklace2, SIZE);
maxBeads = findMaxBeads(necklace2, SIZE * 2);
checkAnswer(necklace, SIZE, maxBeads);
printf("The max number of beads is %d\n", maxBeads);
}
int findMaxBeads(char neck2[], int size)
{
int brk;
int maxBeads;
int leftI, rightI, leftCount = 0, rightCount=0, totalCount, maxCount = 0;
char leftColor, rightColor;
for(brk = 0; brk < 2 * SIZE - 1; brk++)
{
leftCount = rightCount = 0;
rightI = brk;
rightColor = neck2[rightI];
if(rightI == 'w')
{
while(rightI == 'w')
{
rightI++;
}
rightColor = neck2[rightI];
}
rightI = brk;
while(neck2[rightI] == rightColor || neck2[rightI] == 'w')
{
rightCount++;
rightI++;
}
if(brk > 0)
{
leftI = brk - 1;
leftColor = neck2[leftI];
if(leftI == 'w')
{
while(leftI == 'w')
{
leftI--;
}
leftColor = neck2[leftI];
}
leftI = brk - 1;
while(leftI >= 0 && neck2[leftI] == leftColor || neck2[leftI] == 'w')
{
leftCount++;
leftI--;
}
}
totalCount = leftCount + rightCount;
if(totalCount > maxCount)
{
maxCount = totalCount;
}
}
return maxCount;
}
void doubleNecklace(char neck[], char doubleNeck[], int size)
{
int i;
for(i = 0; i < size; i++)
{
doubleNeck[i] = neck[i];
doubleNeck[i+size] = neck[i];
}
}
I didn't study the code in detail, but something is not symmetric: in the for loop, the "left" code has an if but the "right" code doesn't. Maybe you should remove that -1 in the for condition and add it as an if for the "right" code:
for(brk = 0; brk < 2 * SIZE; brk++)
{
leftCount = rightCount = 0;
if (brk < 2 * SIZE - 1)
{
rightI = brk;
rightColor = neck2[rightI];
//...
}
if(brk > 0)
{
leftI = brk - 1;
leftColor = neck2[leftI];
//...
}
//...
Just guessing, though... :-/
Maybe you should even change those < for <=.

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.