Something I'm misunderstanding about rand() % i? [closed] - c++

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 6 years ago.
Improve this question
int main() {
const int n = 5;
int A[n][n]; // value of each cell
int V[n][n]; // total value of each cell
for (int i = 0; i < n; i++)
{
for (int j = 0; j < n; j++)
{
V[i][j] = 0; // initialize total value of each cell equal to zero
A[i][j] = rand() % 10; // set each cell's value equal to some number 0-9
printf("%i ", A[i][j]);
}
printf("\n");
}
for (int i = 0; i < n; i++)
{
for (int j = 0; j < n; j++)
{
if (i == 0 && j == 0)
{
V[i][j] = A[i][j];
}
else if (i == 0)
{
V[i][j] = V[i][j - 1] + A[i][j];
}
else if (j == 0)
{
V[i][j] = V[i - 1][j] + A[i][j];
}
else
{
if (V[i][j - 1] > V[i - 1][j])
{
V[i][j] = V[i][j - 1] + A[i][j];
}
else
{
V[i][j] = V[i - 1][j] + A[i][j];
}
}
}
}
printf("\n");
for (int i = 0; i < n; i++)
{
for (int j = 0; j < n; j++)
{
if (V[i][j] < 10) printf(" %i ", V[i][j]);
else printf("%i ", V[i][j]);
}
printf("\n");
}
cin.get();
}
This outputs http://i.imgur.com/Ak3KpPr.png
What I don't understand is why V[0][2] outputs 12 when it should output V[0][1] + A[0][2], or 7+4.
Context:
At a garage sale one day, you stumble upon an old school video game. In this video game, your
character must take a journey along an n × n grid, collecting rewards along the way. Specifically,
there is an n × n matrix A with nonnegative entries, and your character collects a reward equal to
Aij if he visits the cell (i, j) of the grid. Your objective is to maximize the sum of rewards collected
by your character.
(a) [4 points]. The rules of level one of the game are as follows. Your character starts at the
top-left corner — i.e., cell (1, 1) — of the grid, and must travel to the the bottom-right corner —
i.e., cell (n, n) — in sequence of steps. At each step, your character is allowed to move either one
cell to the right or one cell down in the grid; stepping upwards, to the left, or diagonally is not
2
allowed. Show how to compute the optimal journey in O(n
2
) time.

Where did you get that idea about 7+4?
Your code clearly says that V[0][2] is V[0][1] + A[2][2]. But on previous iteration of your cycle V[0][1] was set to V[0][0] + A[0][1]. And on yet previous iteration of your cycle V[0][0] was set to A[0][0].
So, V[0][0] is 1. Which makes V[0][1] = 1 + 7 = 8. Which makes V[0][2] = 8 + 4 = 12.
Everything is as you implemented it.

Related

Find a sum of all positive matrix elements that located before of the largest positive element

here is what i tried before:
//finding maximum
for (int i = 0; i < n; ++i)
{
for (int j = 0; j < n; ++j)
{
if (arr[i][j] > max)
{
max = arr[i][j];
imax = i;
jmax = j;
}
}
}
//finding a sum
for (int i = 0; i < n; ++i)
{
for (int j = 0; j < n; ++j)
{
if (arr[i][j] > 0)
{
if (i <= imax && j < jmax)
sum += arr[i][j];
}
}
}
cout << "sum = " << sum << endl;
}
but that algorithm doesn't count it right, how should i do to make it work?
looks like that my code is "limitng" the range of search, because of wrong condition and i duuno how to make it right?
Let's think step by step.
Assuming, imax is the row number and jmax is the column number of the maximum elements present in the matrix.
Row selection procedure:
So, to accomplish our object, we will traverse row which is <= imax. That means, we'll consider the value of the current row as our answer only if current row <= imax. If the current row becomes larger than row, then we can stop traversing .
//finding a sum
for (int i = 0; i < n; ++i)
{
for (int j = 0; j < n; ++j)
{
if (arr[i][j] > 0)
{
if(i <= imax)
{
// do something
}
else
{
break;
}
}
}
}
We can also do it in below way:
//finding a sum
for (int i = 0; i < n && i <= imax; ++i)
{
for (int j = 0; j < n; ++j)
{
if (arr[i][j] > 0)
{
}
}
}
Column selection procedure:
It's a little bit different from the row selection procedure.
We can consider every column unless current row is equal to imax. That means when
current row < imax we will consider values of every column, but when current row == imax we'll only consider smaller column's value as our answer.
//finding a sum
for (int i = 0; i < n && i <= imax; ++i)
{
for (int j = 0; j < n; ++j)
{
if(i < imax && arr[i][j] > 0)
{
// consider the value for answer
}
else
{
// here i == imax
// so we'll only consider smaller column's value as our answer
if(j < jmax && arr[i][j] > 0)
{
// consider the value for answer
}
else if(j >= jmax) // we've come out of the boundary. No matter the value is positive or negative, we don't need to check any further
{
break;
}
}
}
}
Overall code of finding sum portion will look like this:
//finding a sum
for (int i = 0; i < n && i <= imax; ++i)
{
for (int j = 0; j < n; ++j)
{
if(i < imax && arr[i][j] > 0)
{
// consider the value for answer
sum += arr[i][j];
}
else
{
// here i == imax
// so we'll only consider smaller column's value as our answer
if(j < jmax && arr[i][j] > 0)
{
// consider the value for answer
sum += arr[i][j];
}
else if(j >= jmax) // we've come out of the boundary. No matter the value is positive or negative, we don't need to check any further
{
break;
}
}
}
}
Note: Don't forget to initialize the value of max , imax, jmax and sum properly.
So this doesn't work the way you've set it up.
Suppose you have a matrix like this:
0 1 5 10 8
4 22 8 18 11
1 2 6 14 9
1 27 6 14 9
1 2 6 14 9
Your max would find that imax = 3, jmax = 1
What happens when you try to count the element at [0, 5]? You miss it because jmax = 1, means all elements to the right of the j =1 column aren't counter by your conditions.
It is not clear what you mean with "located before", but I am almost certain that this is the issue in your code. Supposed the max element is x then you add all elements marked with o and exclude elements marked with .:
ooo...
ooo...
oox...
......
......
But I'd rather expect either this
oooooo
oooooo
oox...
......
......
or this:
ooo...
ooo...
oox...
oo....
oo....

How do I write a code in C++ for fitting a quadratic polynomial to a dataset? [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 2 years ago.
Improve this question
I'm not brilliant at coding, I'm just starting off and the code I created runs with that many errors I feel like I should just start again, but I have no clue what to do differently.
Below is the code I'm running that's coming back with all the errors, I just can't put my finger on what I'm doing wrong and it's so overwhelming.
Please help if you can, thank you x
Edit: sorry I forgot to add the errors! I've got 23 errors, most are 'array type is not assignable' and 'expression did not evaluate to a constant'
#include<iomanip>
#include<cmath>
using namespace std;
int main()
{
int i, j, k, n, N;
cout.precision(4); //set precision
cout.setf(ios::fixed);
cout << "\nEnter the no. of data pairs to be entered:\n"; //To find the size of arrays that will store x,y, and z values
cin >> N;
double x[N], y[N];
cout << "\nEnter the x-axis values:\n"; //Input x-values
for (i = 0; i < N; i++)
cin >> x[i];
cout << "\nEnter the y-axis values:\n"; //Input y-values
for (i = 0; i < N; i++)
cin >> y[i];
cout << "\nWhat degree of Polynomial do you want to use for the fit?\n";
cin >> n; // n is the degree of Polynomial
double X[2 * n + 1]; //Array that will store the values of sigma(xi),sigma(xi^2),sigma(xi^3)....sigma(xi^2n)
for (i = 0; i < 2 * n + 1; i++)
{
X[i] = 0;
for (j = 0; j < N; j++)
X[i] = X[i] + pow(x[j], i); //consecutive positions of the array will store N,sigma(xi),sigma(xi^2),sigma(xi^3)....sigma(xi^2n)
}
double B[n + 1][n + 2], a[n + 1]; //B is the Normal matrix(augmented) that will store the equations, 'a' is for value of the final coefficients
for (i = 0; i <= n; i++)
for (j = 0; j <= n; j++)
B[i][j] = X[i + j]; //Build the Normal matrix by storing the corresponding coefficients at the right positions except the last column of the matrix
double Y[n + 1]; //Array to store the values of sigma(yi),sigma(xi*yi),sigma(xi^2*yi)...sigma(xi^n*yi)
for (i = 0; i < n + 1; i++)
{
Y[i] = 0;
for (j = 0; j < N; j++)
Y[i] = Y[i] + pow(x[j], i) * y[j]; //consecutive positions will store sigma(yi),sigma(xi*yi),sigma(xi^2*yi)...sigma(xi^n*yi)
}
for (i = 0; i <= n; i++)
B[i][n + 1] = Y[i]; //load the values of Y as the last column of B(Normal Matrix but augmented)
n = n + 1; //n is made n+1 because the Gaussian Elimination part below was for n equations, but here n is the degree of polynomial and for n degree we get n+1 equations
cout << "\nThe Normal(Augmented Matrix) is as follows:\n";
for (i = 0; i < n; i++) //print the Normal-augmented matrix
{
for (j = 0; j <= n; j++)
cout << B[i][j] << setw(16);
cout << "\n";
}
for (i = 0; i < n; i++) //From now Gaussian Elimination starts(can be ignored) to solve the set of linear equations (Pivotisation)
for (k = i + 1; k < n; k++)
if (B[i][i] < B[k][i])
for (j = 0; j <= n; j++)
{
double temp = B[i][j];
B[i][j] = B[k][j];
B[k][j] = temp;
}
for (i = 0; i < n - 1; i++) //loop to perform the gauss elimination
for (k = i + 1; k < n; k++)
{
double t = B[k][i] / B[i][i];
for (j = 0; j <= n; j++)
B[k][j] = B[k][j] - t * B[i][j]; //make the elements below the pivot elements equal to zero or elimnate the variables
}
for (i = n - 1; i >= 0; i--) //back-substitution
{ //x is an array whose values correspond to the values of x,y,z..
a[i] = B[i][n]; //make the variable to be calculated equal to the rhs of the last equation
for (j = 0; j < n; j++)
if (j != i) //then subtract all the lhs values except the coefficient of the variable whose value is being calculated
a[i] = a[i] - B[i][j] * a[j];
a[i] = a[i] / B[i][i]; //now finally divide the rhs by the coefficient of the variable to be calculated
}
cout << "\nThe values of the coefficients are as follows:\n";
for (i = 0; i < n; i++)
cout << "x^" << i << "=" << a[i] << endl; // Print the values of x^0,x^1,x^2,x^3,....
cout << "\nHence the fitted Polynomial is given by:\ny=";
for (i = 0; i < n; i++)
cout << " + (" << a[i] << ")" << "x^" << i;
cout << "\n";
return 0;
}
You have in your code several variables which are declared as double x[N], where N is a variable that is known only at run-time. This is not guaranteed to be supported. Instead, you should use a std::vector, initialized like this: std::vector<double> x(N). This creates a vector of doubles of size N, zero-initialized. Look up how to use vectors here: https://en.cppreference.com/w/cpp/container/vector . Also, you should use descriptive variable names, which will help you read and understand your own code (and others you're asking for help). Don't be afraid of 23 error messages, I routinely get 100+ on first compilation of a fresh batch of code. Often they can cascade where one causes a lot of others down the line, so work starting from the one that's earliest in the code, recompiling after every bugfix. The 100+ effectively become 30 or so, sometimes.
Also, it would be helpful to split your function into several functions, and test each one individually, then bring them all together.

looping through a 2D array (diagonal) c++

So I initialized an array as array[8][8] let's suppose that I'm at point (row, column) and for example, it is row 4 column 4 and I want to loop through every diagonal direction (southeast, southwest, northeast, northwest)
so I wrote 4 different functions to check each direction alone, and here is an example for Northeast
for(int i = 0; i < 8; i++)
for(int j = 0; j < 8; j++)
if(array[i - 1][j+1] == 'x')
{
count = count + 1;
}
is there is a way to loop in all diagonal directions at the same time?
another problem is what about getting out of bounds, like if the point is (7,7), then there will be no value in northeast because it will exceed the array bounds array[6][8], and that is out of array bounds. How can I deal with this problem? or does the compiler return an error when it happens?
You can of course check in each direction, e.g.
for(int i = 0; i < 8; i++) {
for(int j = 0; j < 8; j++) {
if (check_north_east(array, i, j))
++count;
if (check_north_west(array, i, j))
++count;
if (check_south_east(array, i, j))
++count;
if (check_south_west(array, i, j))
++count;
}
}
The compiler will happily go beyond the array bounds. So you must make sure, the code won't do it, and check yourself
const int NROWS = 8, NCOLS = 8;
bool check_north_east(char array[][NCOLS], int row, int col)
{
if (row <= 0 || col >= NCOLS - 1)
return false;
return array[row - 1][col + 1] == 'x';
}

SIGSEGV(signal 11) 'segmentation fault' in FCTRL2 codechef

I am facing SIGSEGV error on submitting solution for codechef small factorial problem code FCTRL2 though the code works fine on ideone
coding language C++ 4.3.2
Example
Sample input:
4
1
2
5
3
Sample output:
1
2
120
6
#include <iostream>
using namespace std;
void fact(int n) {
int m = 1, a[200];
for (int j = 0; j < 200; j++) {
a[j] = 0;
}
a[0] = 1;
for (int i = 1; i <= n; i++) {
int temp = 0;
for (int j = 0; j < m; j++) {
a[j] = (a[j] * i) + temp;
temp = a[j] / 10;
a[j] %= 10;
if (temp > 0) {
m++;
}
}
}
if (a[m - 1] == 0) {
m -= 1;
}
for (int l = m - 1; l >= 0; l--) {
cout << a[l];
}
}
int main() {
int i;
cin >> i;
while (i--) {
int n;
cin >> n;
fact(n);
cout << endl;
}
return 0;
}
Caveat I'm not going to just fix up your code for you straight up, but I will highlight where it's going wrong and why you get the seg fault.
Your problem is with your implementation of how you're trying to handle the digit by digit multiplication - specifically with what happens to your m value. Test it out by outputting m each time it's incremented - you'll find it's incrementing more often than you intend. You're right to realise you need to use an approach to get to 158 digits and your basic concept could be made to work.
The first clue is by testing with n = 6 when you get a leading 0 that you shouldn't even though you try to get rid of that problem with the if block that contains m-=1
Try with n = 25 and you will see a lot of leading zeros.
Any value greater than this will fail with a Segmentation error. The Seg fault is because, with this error, you try to set values of the array a beyond the max index (as m gets greater than 200)
N.B. Your assertion that the code works on Ideone.com is only true up to a point - it will fail with n > 25.
(Erased code computing a factorial using int)
The problem in your code is that you increment m each time temp is not 0 for each digit multiplication. You may then get a SIGSEGV when computing big factorials because m becomes too big. You probably saw it because 0 shows up in front of your result. I guess this is why you added the
if (a[m - 1] == 0) {
m -= 1;
}
You should only increment m when the inside loop is finished and term is not null. Once fixed you can get rid of the above code.
void fact(int n) {
int m = 1, a[200];
for (int j = 0; j < 200; j++) {
a[j] = 0;
}
a[0] = 1;
for (int i = 1; i <= n; i++) {
int temp = 0;
for (int j = 0; j < m; j++) {
a[j] = (a[j] * i) + temp;
temp = a[j] / 10;
a[j] %= 10;
}
// if (temp > 0) {
// a[m++] = temp;
// }
while (temp > 0)
{
a[m++] = temp%10;
temp /= 10;
}
}
for (int l = m - 1; l >= 0; l--) {
cout << a[l];
}
}

Sudoku solving matrix, while statement gives an infinite loop

This code should produce a solved sudoku matrix, however the while statement puts it in an infinite loop. Removing the while statement gives me a matrix with some values still 99 or 0. And i can't generate 9 random numbers uniquely one by one.
IF YOU WANT TO RUN AND CHECK THE CODE, REMOVE THE WHILE STATEMENT.
int a[9][9];
int b[9][9];
int inputvalue(int x, int y, int value) //checks horizontally, vertically and 3*3matrix for conflicts
{
int i, j;
for (i = 0; i < 9; i++)
{
if (value == a[x][i] || value == a[i][y])
return 0;
}
for (i = (x / 3) * 3; i <= ((x / 3) * 3) + 2; i++)
{
for (j = (y / 3) * 3; j <= ((y / 3) * 3) + 2; j++)
if (b[i][j] == value)
return 0;
}
return value;
}
int main()
{
int i, j, k;
unsigned int s;
cout << "sudoku\n";
time_t t;
s = (unsigned) time(&t);
srand(s);
for (i = 0; i < 9; i++)
{
for (j = 0; j < 9; j++)
a[i][j] = 99;
}
for (i = 0; i < 9; i++)
{
for (j = 1; j <= 9; j++)//j is basically the value being given to cells in the matrix while k assigns the column no.
while(a[i][k]==99||a[i][k]==0)
{
k = rand() % 9;
a[i][k] = inputvalue(i, k, j);
}
}
for (i = 0; i < 9; i++)
{
for (j = 0; j < 9; j++)
{
cout << a[i][j] << " ";
}
cout << endl;
}
return 0;
getch();
}
You are using assignment =, instead of equality == here:
while(a[i][k]=99||a[i][k]=0)
^ ^
this should be:
while(a[i][k]==99||a[i][k]==0)
a[i][k]=99 will always evaluate to true since 99 is non-zero, although your original code does not compile for me under gcc as it is, so I suspect the code you are running either has some parenthesizes or is slightly different.
Also using k in the while loop before it is initialized is undefined behavior and it is unclear that your termination logic makes sense for a k that is constantly changing for each loop iteration.
Another source of the infinite loop is inputvalue which seems to get stuck returning 0 in some instances, so you need to tweak that a bit to prevent infinite loops.
Also, srand(time(NULL)); is a more common way to initialize the pseudo-random number generator