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(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);
else
assert(m.element(i, j) == NULL_TELEM);
And I got a surprise to see that m.element(4,j) will be 0 for j in the range (0,8) and only 3 for j=9.
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[1000];
this->values_capacity = 1;
this->values_size = 0;
this->lines = new int[nrLines + 1];
this->columns = new TElem[1000];
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 + 1; i <= this->nr_lines; i++)
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's pretty weird that is sees those positions having the value 0.
So having the next test that starts in the next way, I get a memory acces violation:
Matrix m(200, 300);
for (int i = m.nrLines() / 2; i < m.nrLines(); i++) {
for (int j = 0; j <= m.nrColumns() / 2; j++)
{
int v1 = j;
int v2 = m.nrColumns() - v1 - 1;
if (i % 2 == 0 && v1 % 2 == 0)
m.modify(i, v1, i * v1);
else
if (v1 % 3 == 0)
m.modify(i, v1, i + v1);
if (i % 2 == 0 && v2 % 2 == 0)
m.modify(i, v2, i * v2);
else
if (v2 % 3 == 0)
m.modify(i, v2, i + v2);
}
The error is thrown in the method "modify" at currCol = this->column[pos];
And if I look into the debugger it looks like:i=168, lines[i]=-842150451, lines[i+1]=10180,pos=-842150451.
Does anybody have any ideas why it looks this way?
Your code has two small errors.
When you try to find the insertion position in modify, you loop over the non-empty elements in the row:
int currCol = 0;
for (; pos < this->lines[i + 1]; i++) {
currCol = this->columns[pos];
if (currCol >= j)
break;
}
Here, you must update pos++ in each iteration instead of i++.
The second error occurs when you insert an element into column 0. The currCol will be zero, but your condition for adding a new element is
if (currCol != j) {
if (!(e == 0))
add(pos, i, j, e);
}
But j is zero, too, so nothing will be inserted. You can fix this by starting with a non-existing column:
int currCol = -1;
Related
#include <vector>
using namespace std;
int solution(int m, int n, vector<vector<int>> puddles) {
const int MAXIMUM = 100;
int paddlePosition = -1;
int pos[MAXIMUM][MAXIMUM] {0}; //type 1
//int pos[MAXIMUM][MAXIMUM]; //type 2
for(auto puddle = puddles.begin(); puddle != puddles.end(); puddle++)
pos[(*puddle)[1] - 1][(*puddle)[0] - 1] = paddlePosition;
pos[0][0] = 1;
for(int i = 1; i < m; i++)
if(pos[0][i] != paddlePosition)
pos[0][i] = pos[0][i - 1];
for(int i = 1; i < n; i++)
if(pos[i][0] != paddlePosition)
pos[i][0] = pos[i - 1][0];
for(int i = 1; i < n; i++)
{
for(int j = 1; j < m; j++)
{
if(pos[i][j] == paddlePosition);
else if(pos[i - 1][j] == paddlePosition && pos[i][j - 1] == paddlePosition)
pos[i][j] = paddlePosition;
else if(pos[i - 1][j] == paddlePosition)
pos[i][j] = pos[i][j - 1];
else if(pos[i][j - 1] == paddlePosition)
pos[i][j] = pos[i - 1][j];
else
pos[i][j] = (pos[i - 1][j] + pos[i][j - 1]) % 1000000007;
}
}
int answer = pos[n - 1][m - 1];
if(answer == paddlePosition)
answer = 0;
return answer;
}
this code has only one difference. pos array have initialization or not.
when i give parameter m = 100, n = 100, puddles = [[1, 1]] and access to pos[99][99], the value doesn't fixed without initialization.
i thought that double for phrase access data continously and boundary of array was initialized already so data will doesn't mattered without initialization(working like lazy initialization). but it was wrong.
why result is difference?
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.
I am attempting the following question from Interviewbit:
Given a m x n grid filled with non-negative numbers, find a path from top left to bottom right which minimizes the sum of all numbers along its path.
NOTE: You can only move either down or right at any point in time.
I have written the following memoized solution:
int minPath(vector<vector<int> > &A, int i, int j, vector<vector<int> > &dp) {
if (dp[i][j] >= 0)
return dp[i][j];
else if (i == A.size() - 1 && j == A[0].size() - 1)
return dp[i][j] = A[i][j];
else if (i == A.size() - 1)
return dp[i][j] = A[i][j] + minPath(A, i, j + 1, dp);
else if (j == A[0].size() - 1)
return dp[i][j] = A[i][j] + minPath(A, i + 1, j, dp);
else
return dp[i][j] = A[i][j] + min(minPath(A, i + 1, j, dp), minPath(A, i, j + 1, dp));
}
int Solution::minPathSum(vector<vector<int> > &A) {
if (A.size() == 0)
return 0;
vector<vector<int> > dp(A.size(), vector<int>(A[0].size(), -1));
return minPath(A, 0, 0, dp);
}
This solution is giving a TLE during submission.
After a while I took a look at the editorial code, and they have followed the tabulation approach as follows:
int minPathSum(vector<vector<int> > &grid) {
if (grid.size() == 0) return 0;
int m = grid.size(), n = grid[0].size();
int minPath[m + 1][n + 1];
for (int i = 0; i < m; i++) {
minPath[i][0] = grid[i][0];
if (i > 0) minPath[i][0] += minPath[i - 1][0];
for (int j = 1; j < n; j++) {
minPath[i][j] = grid[i][j] + minPath[i][j-1];
if (i > 0) minPath[i][j] = min(minPath[i][j], grid[i][j] + minPath[i-1][j]);
}
}
return minPath[m-1][n-1];
}
According to me, the time complexity of both the codes seem same, yet mine seems to be giving TLE. Where exactly am I going wrong?
The test cases have negative numbers in the grid ( though they have explicitly mentioned non-negative numbers). So dp[i][j] can be negative but your function will never consider those values. Just used another vector to store the visited cell and it got accepted.
int minPath(vector<vector<int> > &A, int i, int j, vector<vector<int> > &dp,vector<vector<bool> > &vis)
{
if (vis[i][j])
return dp[i][j];
vis[i][j] = 1;
if (i == A.size() - 1 && j == A[0].size() - 1)
return dp[i][j] = A[i][j];
else if (i == A.size() - 1)
return dp[i][j] = A[i][j] + minPath(A, i, j + 1, dp, vis);
else if (j == A[0].size() - 1)
return dp[i][j] = A[i][j] + minPath(A, i + 1, j, dp, vis);
else
return dp[i][j] = A[i][j] + min(minPath(A, i + 1, j, dp, vis), minPath(A, i, j + 1, dp, vis));
}
int Solution::minPathSum(vector<vector<int> > &A)
{
if (A.size() == 0)
return 0;
vector<vector<int> > dp(A.size(), vector<int>(A[0].size(), -1));
vector<vector<bool> > vis(A.size(), vector<bool>(A[0].size(), 0));
return minPath(A, 0, 0, dp, vis);
}
I was wondering how I can loop through a two dimentional array if the size of the array is random, e.g 6x6 or 10x10 etc. The idea is to search for four of the same kind of characters, 'x' or 'o'. This is typically needed for a board game.
int main() {
int array_size = 5; // Size of array
int array_height = array_size;
bool turn = true; // true = player 1, false = player 2
bool there_is_a_winner = false;
char** p_connect_four = new char*[array_size];
for (int i = 0; i < array_size; i++) // Initialise the 2D array
{ // At the same time set a value "_" as blank field
p_connect_four[i] = new char[array_size];
for (int j = 0; j < array_size; j++) {
p_connect_four[i][j] = '_';
}
}
}
This is what I have so far, checking from [3][0] to [0][3]. But this requires me to add 2 more for loops to check [4][0] to [0][4] and [4][1] to [1][4] IF the size of the board was 5x5.
for (int i = 3, j = 0; i > 0 && j < array_size; i--, j++ ) {// CHECK DOWN up right from 3,0 -> 0,3
if (p_connect_four[i][j] == p_connect_four[i - 1][j + 1] && p_connect_four[i][j] != '_' ) {
check_diagonalRight++;
if (check_diagonalRight == 3) {
there_is_a_winner = true;
break;
}
}
else {
check_diagonalRight = 0;
}
}
if (there_is_a_winner) { // Break while loop of game.
break;
}
Obviously I want to check the whole board diagonally to the right regardless of the size of the board. Is there any other way than having 3 separate for loops for checking
[3][0] -> [0][3] , [4][0] -> [0][4] and [4][1]-> [1][4] ?
for (i = array_size - 1, j = array_size - 2;
i < array_size && i >= 0, j < array_size && j >= 0; j--)
{ // starts from [4][3] and loops to the left if arraysize = 5x5
// but works on any size
int k = i, l = j;
for (k, l; k < array_size && k > 0, l < array_size && l > 0; k--, l++)
{ // checks diagonally to the right
if (check_diagonalRight == 3)
{
there_is_a_winner = true;
break;
}
if (p_connect_four[k][l] == p_connect_four[k - 1][l + 1] &&
p_connect_four[k][l] != '_')
{ //check up one square and right one square
check_diagonalRight++;
}
else
{
check_diagonalRight = 0;
// if its not equal, reset counter.
}
}
if (there_is_a_winner)
{
break; // break for loop
}
}
if (there_is_a_winner)
{
break; // break while loop of game
}
This checks up and right no matter the size, implement it for the other angles as well and it will work for any board size. You could potentially check right and left diagonal at once with nested loops.
This will work perfectly fine for your program! I hope so!
int arraySize = 8;
for(int i=0, j=0; i<arraySize && j<arraySize; i++, j++)
{
if((i == 0 && j == 0) || (i == arraySize - 1 && j == arraySize - 1))
{
continue;
}
else
{
int k = i;
int l = j;
//This Loop will check from central line (principal diagonal) to up right side (like slash sign / (representing direction))
for(k, l; k>0 && l < arraySize - 1; k--, l++)
{
//Here check your condition and increment to your variable. like:
if (p_connect_four[k][l] == p_connect_four[k - 1][l + 1] && p_connect_four[k][l] != '_' )
{
check_diagonalRight++;
}
}
//You can break the loop here if check_diagonalRight != k then break
k = i;
l = j;
//This Loop will check from central line (principal diagonal) to down left side (like slash sign / (representing direction))
for(k, l; k<arraySize - 1 && l > 0; k++, l--)
{
//Here check your condition and increment to your variable. like:
if (p_connect_four[k][l] == p_connect_four[k + 1][l - 1] && p_connect_four[k][l] != '_' )
{
check_diagonalRight++;
}
}
if(check_diagonalRight == i+j+1)
{
there_is_a_winner = true;
break;
}
}
}
I suggest to surround your board with extra special cases to avoid to check the bound.
To test each direction I suggest to use an array of offset to apply.
Following may help:
#include <vector>
using board_t = std::vector<std::vector<char>>;
constexpr const std::size_t MaxAlignment = 4;
enum Case {
Empty = '_',
X = 'X',
O = 'O',
Bound = '.'
};
enum class AlignmentResult { X, O, None };
// Create a new board, valid index would be [1; size] because of surrounding.
board_t new_board(std::size_t size)
{
// Create an empty board
board_t board(size + 2, std::vector<char>(size + 2, Case::Empty));
// Add special surround.
for (std::size_t i = 0; i != size + 2; ++i) {
board[0][i] = Case::Bound;
board[size + 1][i] = Case::Bound;
board[i][0] = Case::Bound;
board[i][size + 1] = Case::Bound;
}
return board_t;
}
// Test a winner from position in given direction.
AlignmentResult test(
const board_t& board,
std::size_t x, std::size_t y,
int offset_x, int offset_y)
{
if (board[x][y] == Case::Empty) {
return AlignmentResult::None;
}
for (std::size_t i = 1; i != MaxAlignment; ++i) {
// Following condition fails when going 'out of bound' thanks to Case::Bound,
// else you have also to check size...
if (board[x][y] != board[x + i * offset_x][y + i * offset_y]) {
return AlignmentResult::None;
}
}
if (board[x][y] == Case::X) {
return AlignmentResult::X;
} else {
return AlignmentResult::O;
}
}
// Test a winner on all the board
AlignmentResult test(const board_t& board)
{
// offset for direction. Use only 4 direction because of the symmetry.
const int offsets_x[] = {1, 1, 1, 0};
const int offsets_y[] = {-1, 0, 1, 1};
const std::size_t size = board.size() - 1;
for (std::size_t x = 1; x != size; ++x) {
for (std::size_t y = 1; y != size; ++y) {
for (std::size_t dir = 0; dir != 4; ++dir) { // for each directions
auto res = test(board, x, y, offsets_x[dir], offsets_y[y]);
if (res != AlignmentResult::None) {
return res;
}
}
}
}
return AlignmentResult::None;
}
I must implement in C++ using diblok The Seeded Region Growing algorithm due to Adams and Bischof which can be found here http://bit.ly/1nIxphj.
It is the fig.2 pseudocode.
After I choose the seeded points using the mouse , it throws this message : Unhandled exception at 0x00416ca0 in diblook.exe: 0xC0000005: Access violation reading location 0x3d2f6e68.
This is the code of the function:
void CDibView::OnLButtonDblClk(UINT nFlags, CPoint point)
{ BEGIN_SOURCE_PROCESSING;
int** labels = new int* [dwHeight];
for(int k = 0;k < dwHeight; k++)
labels[k] = new int[dwWidth];
int noOfRegions = 2;
double meanRegion[2];
double noOfPointsInRegion[2];
for(int i = 0; i < dwHeight ; i++)
for(int j = 0; j < dwWidth ; j++)
{
labels[i][j] = -1;
}
if(noOfPoints < 6)
{
CPoint p = GetScrollPosition() + point;
pos[noOfPoints].x = p.x;
pos[noOfPoints].y = p.y;
int regionLabel = 0;
if(noOfPoints <= noOfPoints / 2)
labels[p.x][p.y] = regionLabel;
else
labels[p.x][p.y] = regionLabel + 1;
noOfPoints++;
}
else
{
// Calculate the mean of each region
for(int i = 0; i < noOfRegions; i++)
{
for(int j = 0 ; j < noOfPoints; j++)
{
if(labels[pos[j].x][pos[j].y] == i)
{
meanRegion[i] += lpSrc[pos[j].x * w + pos[j].y];
}
}
meanRegion[i] /= 3;
noOfPointsInRegion[i] = 3;
}
for(int seedPoint = 0; seedPoint < noOfPoints; seedPoint++)
{
// define list
node *start, *temp;
start = (node *) malloc (sizeof(node));
temp = start;
temp -> next = NULL;
for(int i = -1; i <= 1; i++)
for(int j = -1; j<= 1; j++)
{
if(i == 0 && j == 0) continue;
int gamma = lpSrc[(pos[seedPoint].x + i) * + pos[seedPoint].y + j] - lpSrc[pos[seedPoint].x * w + pos[seedPoint].y];
push(start, pos[seedPoint].x + i, pos[seedPoint].y + j, gamma);
}
sort(start);
if(start != NULL)
{
node *y = start;
pop(start);
int sameNeighbour = 1;
int neighValue = -1;
for(int k = -1; k <= 1; k++)
for(int l = -1; l <= 1;l++)
{
if(k ==0 && l==0) continue;
if(labels[y -> x + k][y -> y + l] != -1)
{
neighValue = labels[y -> x + k][y -> y + l];
break;
}
}
for(int k = -1; k <= 1; k++)
for(int l = -1; l <= 1;l++)
{
if(k == 0 && l==0) continue;
if(labels[y -> x + k][y -> y = 1] != -1 && labels[y -> x + k][y -> y + l] != neighValue)
sameNeighbour = 0;
}
if(sameNeighbour == 1)
{
labels[y -> x][y -> y] = neighValue;
meanRegion[neighValue] = meanRegion[neighValue] * noOfPointsInRegion[neighValue] / noOfPointsInRegion[neighValue] + 1;
noOfPointsInRegion[neighValue]++;
for(int k = -1; k <= 1; k++)
for(int l = -1; l <= 1;l++)
{
if(k == 0 && l == 0) continue;
if(labels[y -> x + k][y -> y + l] == -1 && find(start, y->x + k, y->y + l) == 0)
{
int gammak = meanRegion[neighValue] - lpSrc[(y->x +k) * w + (y->y + l)];
push(start, y->x + k, y->y + l, gammak);
sort(start);
}
}
}
else
{
labels[y->x][y->y] = -1;
}
}
}
int noOfRegionOne = 0;
int noOfRegionTwo = 0;
int noOfBoundary = 0;
for(int i = 0; i< dwHeight; i++)
for(int j = 0;j<dwWidth; j++)
{
if(labels[i][j] == -1)
noOfBoundary++;
else if(labels[i][j] == 0)
noOfRegionOne++;
else if(labels[i][j] == 1)
noOfRegionTwo++;
}
CString info;
info.Format("Boundary %d, One %d, Two %d", noOfBoundary, noOfRegionOne, noOfRegionTwo);
AfxMessageBox(info);
noOfPoints = 0;
}
CScrollView::OnLButtonDblClk(nFlags, point);
END_SOURCE_PROCESSING;
}
After a choose to break the running, this is what is shown http://postimg.org/image/j2sh9k0a1/
Can anybody tell what is wrong and why it doesn't work?
Thanks.
Your screenshot shows that your node (Y is a terrible name, incidentally) has garbage values in it. Offhand, I suspect that 'sort' is overwriting your node values, resulting in garbage. I would create a static copy of your current node to prevent it from changing during processing:
Change
node *y = start;
pop(start);
to
node y = *start;
pop(start);