What is wrong with this bit of code? [closed] - c++

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions concerning problems with code you've written must describe the specific problem — and include valid code to reproduce it — in the question itself. See SSCCE.org for guidance.
Closed 9 years ago.
Improve this question
I am trying to augment a matrix with an identity matrix of similar dimensions, why is this bit of code not working?
It keeps giving the error 'vector subscript out of range'
for (i = 0; i < matrix.size(); i++)
for (j = matrix.size(); j < 2 * matrix.size(); j++)
if (i == j % matrix.size())
matrix[i][j] = 1;
else
matrix[i][j] = 0;

For a square matrix I think you are initialising j incorrectly?
for (i = 0; i < matrix.size(); i++)
for (j = 0; j < matrix.size(); j++)
if (i == j)
matrix[i][j] = 1;
else
matrix[i][j] = 0;
Edit: So to augment I think the following to extend the length of the rows
(http://en.wikipedia.org/wiki/Augmented_matrix)
for (i = 0; i < matrix.size(); i++)
matrix[i].resize(2 * matrix.size())
for (j = matrix.size(); j < 2 * matrix.size(); j++)
if (i == j % matrix.size())
matrix[i][j] = 1;
else
matrix[i][j] = 0;

You have to resize each row-vector (or row-array maybe) first. Otherwise the cell you try to access will be outside of your row range (and you receive the corresponding error).
You can do this by matrix[row].resize(2*matrix[row].size());, where row = 0 .. matrix.size()-1.

Related

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

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.

C++ code not running as it should be [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 7 years ago.
Improve this question
Here is my C++ code for counting sort algorithm , there is no errors as well as no warnings but when I want to execute it it's give me "Counting.exe has stopped working" I think it is a run time error.
void Counting_sort()
{
int A[]={5,15,20,30,40,8,36,25,96,15,40,15,96,47,20};
int k = 15 ;
int n = 15;
int i, j;
int B[15];
int C[100];
for(i = 0; i <= k; i++)
C[i] = 0;
for(j =1; j <= n; j++)
C[A[j]] = C[A[j]] + 1;
for(i = 1; i <= k; i++)
C[i] = C[i] + C[i-1];
for(j = n; j >= 1; j--)
{
B[C[A[j]]] = A[j];
C[A[j]] = C[A[j]] - 1;
}
cout << "\nThe Sorted array is : ";
for(i = 1; i <= n; i++)
cout << B[i] << " " ;
}
void main()
{
Counting_sort();
}
for(j = n; j >= 1; j--)
{
// You are accessing A[j]
}
So A[15] is a invalid access and will lead to undefined behavior.
The valid access for array A[15] is A[0] to A[14] anything other than this is array out of bound access.

Nested loop with arrays having repeating numbers [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
I have an array that keeps the number of each element.
int total[5] = {2,3,4,5,6}
int num = 5; //array total has 5 elements
This means that we have 2 element 0's, 3 element 1's in our original array. We are not worried about the original array since I already have a code to keep the number of the elements.
I need a nested for loop that creates a new array that looks like this:
array[0] = 1;
array[1] = 1;
array[2] = 5;
array[3] = 5;
array[4] = 5;
array[5] = 9;
array[6] = 9;
array[7] = 9;
array[8] = 9;
and so on. That is, we store a value in our new array as many as the its value in "total" array. Values 1,5,9, etc. are stored in an array called element. I have something like this so far:
for (int i = 0; i < num; i++){
for (int j = 0; j < total[i]; j++){
array[i + j] = element[i];
}
}
Can somebody help me to figure this out?
An easy solution (though not necessarily elegant) is to do the following:
int count = 0;
for (int i = 0; i < num; i++){
for (int j = 0; j < total[i]; j++){
array[count] = element[i];
count++;
}
}
then you don't need to worry about trying to figure out what position you are at for the array.
You need to track the number of the elements:
int sum = 0;
for (int i = 0; i < num; i++){
for (int j = 0; j < total[i]; j++){
array[sum + j] = element[i];
}
sum += total[i];
}

Implementation of CountSort [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
So to cut a long story short, I am trying to implement countsort for vector. I have some error somewhere in my code, though I think that I have followed the pseudo code pretty strictly.
The function:
void csort(vector<int>& a, vector<int>& b)
{
vector<int> c(a.size());
for(int i = 0; i <= c.size(); i++)
c[i] = 0;
for(int i = 0; i <= a.size(); i++ )
{
c[a[i]]++;
}
for(int i = 0; i <= c.size(); i++)
{
c[i]+= c[i-1];
}
for(int i = a.size(); i < 1; i--)
{
b[c[a[i]]] = a[i];
c[a[i]] =c[a[i]] -1;
}
}
The pesudo code:
let C[k] be a new array
for i = 0 to k
C[i] = 0
for j = 1 to A:length
C[A[j]] = C[A[j]] +1
for i = 1 to k
C[i] = C[i]+ C[i-1]
for j = A:length downto 1
B[C[A[j]]] = A[j]
C[A[j]] = C[A[j]] -1
The code as it is is very unreadable and error prone. In any case, what I first saw is that in the snippet below you will access c[-1] at the first iteration, thus incurring in undefined behaviour.
for (int i = 0; i <= c.size(); i++)
{
c[i] += c[i-1]; // Evaluation of c[i-1] is illegal for i == 0
}
for(int i = a.size(); i < 1; i--)
This code won't work at all.
for j = A:length downto 1
↑
To implement this pseudo code, you should do like this
for(int i(a.size()-1);i>=0;--i)
And for code like this( c[a[i]] ),you will get run-time error if a[i]<0 or a[i]>=c.size()

How to put NULL in all cells of a matrix vector?

i'm trying to initialize all cells of a matrix with NULL values, but something is wrong here.
the code :
vector<vector<Distance*> > distanceMatrix;
for (int i = 0; i < 7 ; i++)
for (int j = 0; j < 7 ; j++)
distanceMatrix[i][j].push_back(NULL);
i bet it's something stupid, thanks for the help.
From the std::vector reference page:
Vectors can be constructed with some values in them.
You may try:
vector<vector<Distance*> > distanceMatrix(7, vector<Distance*>(7, NULL));
Also, regarding your problem:
vector<vector<Distance*> > distanceMatrix;
for (int i = 0; i < 7 ; i++)
for (int j = 0; j < 7 ; j++)
distanceMatrix[i][j].push_back(NULL); //1
When you code first reach //1, distanceMatrix[i] resolves to distanceMatrix[0] but you did not call distanceMatrix.push_back(vector<Distance*>()) so you are referring to a non initialized cell.
To correct code would have been:
vector<Distance*> vec;
for (int j = 0; j < 7 ; j++)
vec.push_back(NULL);
vector<vector<Distance*> > distanceMatrix;
for (int i = 0; i < 7 ; i++)
{
distanceMatrix.push_back(vec);
}
Which is still far worse than my first suggestion.
Since the matrix is empty to begin with, you need to push_back every value and every row, not depending on its position in the matrix:
vector<Distance*> row;
for(int j=0; j < 7; j++)
row.push_back(NULL);
vector<vector<Distance*> > distanceMatrix;
for(int i=0; i < 7; i++)
distanceMatrix.push_back(row);