Sort Function Deleting portion of array, C - c++

I have this very weird issue going on. The function you will see in a moment is supposed to ensure that all elements (chars) in a 2D array are at there utmost position, that is, there is no empty space above any of the characters. For instance a board could look like this:
1 X * * X ^
2 * X ^ *
3 o o * X ^
4 o ^ X X X
5 ^ * X * ^
1 2 3 4 5
And there is an issue at (2,1) because there is an empty space above a non empty space.
My function does the sorting correctly but it deletes any character in the bottom row that has an empty space above it. I cannot, for the life of me, figure out why. Here is my sort function.
int bb_float_one_step(BBoard board){
int i,j;
for (i = 0; i < board->rows; i++){
for (j = 0; j < board->cols; j++){
if (board->boardDim[i][j] == None && (board->boardDim[i + 1][j] != None && i + 1 <= board->rows)){
char tmp = board->boardDim[i + 1][j];
board->boardDim[i + 1][j] = board->boardDim[i][j];
board->boardDim[i][j] = tmp;
}
}
}
for (i = 0; i < board->rows; i++){
for (j = 0; j < board->cols; j++){
printf("%c",board->boardDim[i][j]);}printf("\n");}
}
Below Is a picture of the full sequence, The Program prints a board. The user is asked to select a region to 'pop.' A function then replaces all the characters that are connected with a blank space. Then in the last portion of the picture you can see how the characters are deleted. The board that doesn't have a border is there because I was using it to check if the characters actually were deleted or not.
Thank you in advanced for 1, reading this whole post, and 2, any help you can give.

Since you are comparing current row with next row you should use for(i = 0; i < board->rows-1; i++)
Then in your complex if statement, get rid of && i <= board->rows. That should have been a less-than anyway, not less-than-or-equals. You're going out of bounds and getting garbage in your array.

You are checking the row beyond the maximum number of rows.
(board->boardDim[i + 1][j] != None && i + 1 <= board->rows)
That memory is not guaranteed to be 0. If it is not 0, your function will swap it in. If it is not human readable, printf won't print anything for it thereby shifting the | to the left.

Related

Appropriate logic for this pattern

How do I print a pattern with number of rows is equal to number of stars such that if 1 star then 1 row of 1 star, 2 star then 2 rows of 2 stars and so on, provided with good logic?
Here's the output for the logic mentioned above
*
**
**
***
***
***
using mod operator you can get proper output.Java has one important arithmetical operator you may not be familiar with, %, also known as the modulus or remainder operator. The % operator returns the remainder of two numbers. For instance 10 % 3 is 1 because 10 divided by 3 leaves a remainder of 1. You can use % just as you might use any other more common operator like + or -.
I write code in java.
Execution Steps:-
for loop for declare i value to 1.loop start with value 1 and last value 5.
for loop for declare i value to 1.in this we gave condition for j is i*i.
if j value is 1 then it print star.
if j value is not 1 then it goes to else part.
in this there are again if and else part in if part we use mod operator and if its value gives 0 value then print star otherwise goto else condition.
for(int i = 1; i <= 5; i++) {
for(int j = 1; j <= i * i; j++) {
if(j == 1) {
System.out.println();
System.out.print("*");
} else if(j % i == 0) {
System.out.print("*");
System.out.println();
} else {
System.out.print("*");
}
}
}

count consecutive 1's in binary

I am writing code in Hackerrank. And recently the problem said, convert decimal to base 2 and then count the max consecutive 1's in the binary number. And first I come with following solution. It works fine. But I do not understand the counting part of it, even though I wrote it.
The code is
int main(){
int n,ind=0, count=0, mmax=0;
char bin[100];
cin >> n;
while(n){
if(n%2==0) {
bin[ind]='0';
n = n / 2;
ind = ind + 1;
}
else if(n%2==1) {
bin[ind]='1';
n = n / 2;
ind = ind + 1;
}
}
for(int i=0; i<=(ind-1); i++){
if(bin[i] == '1' && bin[i+1] == '1'){
count++;
if(mmax < count)
mmax = count;
}
else
count=0;
}
cout << mmax + 1 << endl;
return 0;
}
In the above code, I guess that variable mmax will give me the max consecutive number of 1's but it gives me value that has (max consecutive - 1), So I just wrote like that and submitted the code. But I am curious about. why it is working that way. I am little bit of confused the way that code works like this.
Thanks
Lets say you have this binary sequence:
11110
Your code will compare starting from the first and second:
|11|110 1 && 1 -> max = 1
1|11|10 1 && 1 -> max = 2
11|11|0 1 && 1 -> max = 3
111|10| 1 && 0 -> max = 3
you can see, that although there are 4 1's you only do 3 comparisons, so your max will always be -1 of the actual max. You can fix this by adding mmax += 1 after your for loop.
Just a little bit of trace using small example will show why.
First, lets say there is only 1 '1' in your array.
Since you require both the current position and your next position to be '1', you will always get 0 for this case.
Let's say I have "11111". At the first '1', since next position is also '1', you increment count once. This repeats until 4th '1' and you increment your count 4 times in total so far. When you reach 5th '1', your next position is not '1', thus your count stops at 4.
In general, your method is like counting gaps between fingers, given 5 fingers, you get 4 gaps.
Side note: your code will fail for the case when there is no '1' in your array.

if-statement executing when it shouldn't (kind of)

int trees = 3;
int tree_x, tree_y;
for(int r = 0; r < m_townsize; r++)
{
for(int c = 0; c < m_townsize; c++)
{
if(r == 0 || c == 0 || r == (m_townsize - 1) || c == (m_townsize - 1))
m_town[r][c] = 'W';
while(trees > 0)
{
tree_x = random() % m_townsize;
tree_y = random() % m_townsize;
cout << tree_y << "," << tree_x << endl;
if(m_town[tree_y][tree_x] == ' ')
{
m_town[tree_y][tree_x] = 'T';
trees -= 1;
}
}
}
}
According the code I have written, if there is a space character at the coordinate of the tree, it should place a tree and lower the tree count by 1.
If there is not a space there, it should skip placing a tree, thus not decrementing. This should cause it to pick another set of coordinates and run through again.
However, if you look at this particular output it is running to the if-statement skipping the first option to replace it with a T--since it is a W--but still decrementing by 1. I don't get it. It should skip the statement all together, not skip just the first line. Netbeans tells me my brackets are right, so it shouldn't be an issue with the assignment belonging to the if and the decrement belonging to the while.
If I make a do-while loop it places a whole bunch. I don't know what's happening.
This output placed 2 trees.
You are walking over each coordinate.
If it is on the edge you put a 'W'. Then you randomly place a tree 'T'.
Then you proceed to the next coordinate.
This means you can place some trees in squares before you overwrite with a 'W'.
Finish all the walls before placing trees. Consider a more efficient way to place walls to, like doing each edge instead of loopimg over the middle abd doing nothing.

Issues with Halide select statement

I'm trying to do some stencil computation using Halide. So assuming a basic 5 point 2D stencil, to evaluate some value at cell i,j I need the values of i-1,j i-2,j, i+1,j i+2,j. Now the way this works in C++ is that I have a for statement:
for(int i = 2; i < max_i - 2; i++)
for(int j = 2; j < max_j - 2; j++)
Calculate out = some_function_of(in(i,j), in(i-1,j), in(i-2,j), in(i+1,j), in(i+2,j))
Now I'm trying to do the same thing with Halide. so I have a Buffer called in which has the same value as my input array in the C++ code. And I have a Func called out:
out(i,j) = select(i >= 2 && j >= 2, some_function_of(in(i,j), in(i-1,j), in(i-2,j), in(i+1,j), in(i+2,j)) ,0.0f)
When I run this code I get the following error:
Error:
Input buffer b0 is accessed at -1, which is before the min (0) in dimension 0
Aborted (core dumped)
From my understanding, the reason for this error is that the select statement evaluates both statements so eventhough I don't want to calculate anything for i and j values less than two, the function is evaluated at i = 0 and j = 0 and thus the invalid address access.
So is there anyway to do this in Halide? Are there any other equivalents for if/else statements?
Using a boundary condition will do what you want:
Func unbounded;
unbounded(i, j,) = some_function_of(in(i,j), in(i-1,j), in(i-2,j), in(i+1,j), in(i+2,j));
out(i, j) = BoundaryConditions::constant_exterior(unbounded, 0.0f, 2, width - 4, 2, height - 4)(i, j);
I believe you can use "Expr()" instead of "width - 4" or "height - 4" if you want the maximum unbounded.
The use if BoundaryConditions functions allows hinting the compiler which direction of the if/else construct is more likely.

Bit-wise shift for Matrix iteration?

Ok some background
I have been working on this project, which I had started back in college, (no longer in school but want to expand on it to help me improve my understanding of C++). I digress... The problem is to find the Best path through a matrix. I generate a matrix filled with a set integer value lets say 9. I then create a path along the outer edge (Row 0, Col length-1) so that all values along it are 1.
The goal is that my program will run through all the possible paths and determine the best path. To simplify the problem I decide to just calculate the path SUM and then compare that to what the SUM computed by the application.
(The title is miss leading S=single-thread P=multi-threads)
OK so to my question.
In one section the algorithm does some simple bit-wise shifts to come up with the bounds for iteration. My question is how exactly do these shifts work so that the entire matrix (or MxN array) is completely traversed?
void AltitudeMapPath::bestPath(unsigned int threadCount, unsigned int threadIndex) {
unsigned int tempPathCode;
unsigned int toPathSum, toRow, toCol;
unsigned int fromPathSum, fromRow, fromCol;
Coordinates startCoord, endCoord, toCoord, fromCoord;
// To and From split matrix in half along the diagonal
unsigned int currentPathCode = threadIndex;
unsigned int maxPathCode = ((unsigned int)1 << (numRows - 1));
while (currentPathCode < maxPathCode) {
tempPathCode = currentPathCode;
// Setup to path iteration
startCoord = pathedMap(0, 0);
toPathSum = startCoord.z;
toRow = 0;
toCol = 0;
// Setup from path iteration
endCoord = pathedMap(numRows - 1, numCols - 1);
fromPathSum = endCoord.z;
fromRow = numRows - 1;
fromCol = numCols - 1;
for (unsigned int index = 0; index < numRows - 1; index++) {
if (tempPathCode % 2 == 0) {
toCol++;
fromCol--;
}
else {
toRow++;
fromRow--;
}
toCoord = pathedMap(toRow, toCol);
toPathSum += toCoord.z;
fromCoord = pathedMap(fromRow, fromCol);
fromPathSum += fromCoord.z;
tempPathCode = tempPathCode >> 1;
}
if (toPathSum < bestToPathSum[threadIndex][toRow]) {
bestToPathSum[threadIndex][toRow] = toPathSum;
bestToPathCode[threadIndex][toRow] = currentPathCode;
}
if (fromPathSum < bestFromPathSum[threadIndex][fromRow]) {
bestFromPathSum[threadIndex][fromRow] = fromPathSum;
bestFromPathCode[threadIndex][fromRow] = currentPathCode;
}
currentPathCode += threadCount;
}
}
I simplified the code since all the extra stuff just detracts from the question. Also if people are wondering I wrote most of the application but this idea of using the bit-wise operators was given to me by my past instructor.
Edit:
I added the entire algorithm for which each thread executes on. The entire project is still a work a progress but here is the source code for the whole thing if any one is interested [GITHUB]
A right bit shift is equivalent to dividing by 2 to the power of the number of bits shifted. IE 1 >> 2 = 1 / (2 ^ 2) = 1 / 4
A left bit shift is equivalent to multiplying by 2 to the power of the number of bits shifted. IE 1 << 2 = 1 * 2 ^ 2 = 1 * 4
I'm not entirely sure what that algorithm does and why it needs to multiply by 2^ (num rows - 1) and then progressively divide by 2.