How do I skip checking for my position - loops

for (int x = 0; x <= battleField.getCols(); x++){
for (int y = 0; y <= battleField.getRows(); y++){
if ((battleField.get(x,y) == team) && ((x + y)
!= battleField.get(row, col)))
{
.
.
.
}
}
}
battleField.get(row, col) will return my position on a grid now my question is that how do I skip my self from checking where my position is ? because when the for loop checks for x and y it goes through the whole grid. What do I have to do?

Assuming the variables for your current position are named current_x and current_y, then you could do something like this inside your loop...
bool isMyPosition = (x == current_x) && (y == current_y);
if ( !isMyPosition
&& (battleField.get(x,y) == team)
&& ((x + y) != battleField.get(row, col)))
{
...
}

Instead of
((x + y) != battleField.get(row, col))
I think you want
(x != row && y != col)
If you did want that first part you could just add this to the beginning of your inner for loop:
for (int x = 0; x <= battleField.getCols(); x++){
for (int y = 0; y <= battleField.getRows(); y++){
if(x == row && y == col) // This will check if the loop is looking at your position
continue; // This will go to the next step in the "y" for loop, essentially skipping the rest of the code in this block
if ((battleField.get(x,y) == team) && ((x + y)
!= battleField.get(row, col)))
{
.
.
.
}
}
}

if(Question.IsAbout(EscapingOnCheck))
Most languages have some kind of continue that can be used to escape a loop when a condition is met.
else
Save your current position in some variables, and add another nested loop (for debugging's sake) or add an && clause (for less code's sake)

Related

How to simplify if statements

How can I simplify below if statements?, I'm trying to achieve the possibly most efficient code.
// doSomething based on x value and y value
void doSomething(x int, y int) {
//x not zero and y not zero
if (x != 0 && y != 0) {
//do a
//do b if x greater or equal y
//else do c
if (x >= y) {
//do b
} else (x < y) {
//do c
}
return;
}
//do b if x not zero and y zero
if (x != 0 && y == 0) {
//do b
return;
}
//do e if both x and y zero
if (x == 0 && y == 0) {
//do e
return;
}
}
What is the most concise and efficient way to simplify?
As it stands, your code is equivalent to:
if (x == 0)
{
if (y == 0)
do e
}
else if (y != 0)
{
if (x < y)
do a,c
else
do a,b
}
In particular:
if x=0 && y!=0 or y=0 && x!=0, then do nothing;
the two branches //do b if x not zero and y zero and //do d if x zero and y not zero are unreachable in your code.
History:
The code in the question was changed several times. This answer is based on the original version of the code. That code is shown below, minimally modified so that it's compilable C code:
void original(int x, int y)
{
if (x == y && x != 0 && y != 0) {
// do a
// do b
return;
}
if (x < y && x != 0 && y != 0) {
// do a
// do c
return;
}
if (x > y && x != 0 && y != 0) {
// do a
// do b
return;
}
if (x != 0 && y == 0) {
// do a
// do b
return;
}
if (x == 0 && y != 0) {
// do a
// do d
return;
}
if (x == 0 && y == 0) {
// do e
return;
}
}
Motivation:
The advantage of the original code is that it clearly covers all possible input combinations.
The first three if statements handle the cases where x and y are non-zero (with x==y, x<y, and x>y handled separately). Then the remaining three if statements handle the cases where one or both are zero. That covers everything.
The disadvantages of the original code are:
Many of the comparisons are repeated several times, e.g. y != 0 is checked four times. Given that branching statements tend to be time consuming in contemporary (year 2021) processors, redundant comparisons are something to be avoided 1.
The code violates the DRY principle. Specifically, do a appears in five locations, and do b appears in three locations. So any refactoring of the code should attempt to eliminate the repetition.
1) The optimizer may be able reduce the number of comparisons. However, that's hard to test without real code.
Refactoring with nested if statements:
If we focus on the DRY principle first, we notice that a appears in 5 of 6 code blocks. Only the case for e doesn't invoke a. So the logical choice is to handle e first. This results in the following code structure:
if (x == 0 && y == 0) {
// do e
} else {
// do a
// everything else (note that either x is not zero, or y is not zero)
}
Within the "everything else", we have do b three times, do c once, and do d once. So the next step is to handle c and d, leaving only b. The refactored code looks like this:
void nestedIf(int x, int y)
{
if (x == 0 && y == 0) {
// do e
} else {
// do a
if (x == 0) {
// do d
} else {
if (y != 0 && x < y) {
// do c
} else {
// do b
}
}
}
}
Refactoring with early return statements:
Some coding standards insist that a function shall only return from one location. The nested if code meets that requirement, but at the cost of being a little messy due to nesting. Using early returns eliminates the nesting, and may allow the code for a thru e to be implemented inline without additional functions (assuming they're only a few lines each). The refactored code looks like this:
void earlyReturn(int x, int y)
{
if (x == 0 && y == 0) {
// do e
return;
}
// do a
if (x == 0) { // x is zero and y is not zero
// do d
return;
}
if (y != 0 && x < y) { // x and y are both not zero, and x < y
// do c
return;
}
// do b
}
assuming a(), b(), and e() have the same type (fxtype)
fxtype *fx[4] = { e, NULL, b, a }; // NULL when x==0, y!=0
fx[2*!!x + !!y](x, y);
Change a to include c() and b()
int a(int x, int y) {
// do previous a()
if (x < y) c(x, y); else b(x, y);
return 0;
}

This is about complex three number

Thats one wrong with my code and I dont have any idea about this wrong
Please be attention to that I can just use from for and while and if
The question is:
Write a code that gets the natural number n then tries to find x,y,z (natural numbers) in some way:
n=x+y+z
Then if the following is true of x, y, z, print these three numbers in the output, otherwise print the Not Found statement:
x = y ^ 2 + z ^ 2
(x or y or z) = i + (i + 1) + (i + 2)
Where i is a natural number.
Be it. Then if the following is true of x, y, z, print these three numbers in the output, otherwise print the Not Found statement:
x = y ^ 2 + z ^ 2
(x or y or z) = i + (i + 1) + (i + 2)
Where i is a natural number.
(Note that the input n is such that the int variable is sufficient and does not overflow.)
Input
The input contains a line in which a natural number is given.
Output
The output must either consist of three lines, each integer x, y, and z, respectively, from small to large, or the expression Not Found.
Example
Sample Input 1
48
Copy
Sample output 1
2 6 40
Copy
Sample input 2
5
Copy
Sample output 2
Not found
#include <stdio.h>
int main() {
int z,x,y,n;
scanf("%u",&n);
for(y=1;y<(n/3);y++) {
for(z=y;z<=((2*n)/3);z++) {
(x=(n-(y+z)));
if(x==((y*y)+(z*z))) {
if(((((y-3)%3)!=0)||(y==3))&&((((z-3)%3)!=0)||(z==3))&&((((x-3)%3)!=0)||(x==3))) {
continue;
}
printf("%d\n",y);
printf("%d\n",z);
printf("%d",x); return 0;
}
}
}
printf("Not found");
return 0;
}
This syntax (if(x==((yy)+(zz))) is wrong. It should be if (x == ((y*y)+(z*z))) or use pow function from math.h library like this (if(x == (pow(y,2)+pow(z,2)))
int main()
{
int z, x, y, n;
scanf("%u", &n);
for (y = 1; y < (n / 3); y++)
{
for (z = y; z <= ((2 * n) / 3); z++)
{
(x = (n - (y + z)));
if (x == ((y*y)+(z*z)))
{
if (((((y - 3) % 3) != 0) || (y == 3)) && ((((z - 3) % 3) != 0) || (z == 3)) && ((((x - 3) % 3) != 0) || (x == 3)))
{
continue;
}
printf("%d\n", y);
printf("%d\n", z);
printf("%d", x);
return 0;
}
}
}
printf("Not found");
return 0;
}

Most efficient way to check for a win in a variable size tic-tac-toe grid?

I'm writing a tic-tac-toe game in C where the user chooses the size of the grid. The grid is a 2D array.
I'm having trouble efficiently checking for a win. This is my current idea:
for(int y = 0; y < gridSize; y++)
{
int lineTotal = 0;
for(int x = 0; x < gridSize; x++)
{
if (grid[x][y] == grid[0][y])
{
lineTotal++;
if (lineTotal == gridSize && grid[x][y] == playersLetter)
{
return 1;
}
}
}
}
Which checks every row for a full line. If I want to check each column, I have to swap x and y re-do each loop. I also have to do another loop to check the diagonals, though that's not too hard seeing as there are only two.
My problem is I want to limit the amount of iterations of all the loops to gridSize^2.
Make this easier: iterate once through the loops, keeping a count of X vs O in each of your combinations:
int row[gridSize], col[gridSize], diag1, diag2
for(int y = 0; y < gridSize; y++)
int lineTotal = 0;
{
for(int x = 0; x < gridSize; x++)
{
if (grid[x][y] == 'X') {
row[x]++
col[y]++
if (x == y) diag1++
if (x+y == gridSize) diag2++
}
else if (grid[x][y] == 'XO {
row[x]--
col[y]--
if (x == y) diag1--
if (x+y == gridSize) diag2--
}
}
}
Now, just check your totals; if any of them reached gridSize, X wins; if -gridSize, O wins.
Perhaps even easier, keep these as running sums through the game. For instance, when X moves into cell x, y:
if (row[x]++ == gridSize) `X` wins
if (col[x]++ == gridSize) `X` wins
if (x == y && diag1[x]++ == gridSize) `X` wins
if (x+y == gridSize and diag[x]++ == gridSize) `X` wins
Also, note that the first one, especially, is easier if you code the grid with -1, 1, and 0 for X, O, and empty.

How does 'if((x) || (y=z))' work?

I don't quite understand how the if statement in this case works. It evaluates the x != 0 statement and when that is not true anymore, it assigns z to y and then breaks the if statement?
int main()
{
int x, y, z, i;
x = 3;
y = 2;
z = 3;
for (i = 0; i < 10; i++) {
if ((x) || (y = z)) {
x--;
z--;
} else {
break;
}
}
printf("%d %d %d", x, y, z);
}
Let's decompose that into smaller bits.
if (x) is the same as if (x != 0). If x != 0, then you know the condition is true, so you don't do the other portion of the if.
If part 1. was false, then y = z assigns z into y and returns the final value of y.
From point 2., we can understand that if (y = z) is equivalent to y = z; if (y != 0)
Thus, from points 1. and 3., we can understand that :
if ((x) || (y = z)) {
doSomething();
}
else {
doSomethingElse();
}
Is the same as :
if (x != 0) {
doSomething();
}
else {
y = z;
if (y != 0) {
doSomething();
}
else {
doSomethingElse();
}
}
It's true it's not particularly readable code though.
No. if ((x) || (y = z)) {
in C-English is basically:
if x is nonzero, evaluate the following code.
if x is zero, set y to z.
if y is nonzero, evaluate the following code.
otherwise, break out of the loop.
If x is zero or y is zero, it breaks out of the loop.
int main()
{
int x = 3;
int y = 2;
int z = 3;
unsigned int i;
for (i = 0; i < 10; i++)
if (x != 0) {
x = x-1;
z = z-1;
}
else {
y = z;
if (y != 0) {
x = x-1;
z = z-1;
}
else {
break;
}
}
}
printf("%d %d %d", x, y, z);
}
In C, there is short-circuiting, so the statement y=z will not be evaluated until x becomes zero.
When x == 0, since z also decrements the same way, z == 0. Hence y will also be zero at that time due to the assignment. The statement y=z also returns y at this point which will be evaluated as a condition, and since that is also 0, the else break will be hit.
Hence I believe the answer should be 0 0 0.
When you use assignment in an if statement, the result of the assignment is returned. so when you write :
if (x = y)
It will be always true unless the value of y is 0, so 0 is returned as the result of assigning and the if statement is not executed.(anything except 0 is considered as true.)
So when you write :
if ( x || (x = y))
The if statement doesn't execute only if x is 0 & y is 0.
Here
if ((x) || (y = z))
there are two condition
one condition is
if ((x)) and another condition is if ((y = z))
if one of them is true then if portion is execute otherwise else condition work
only and only when both condition are false then else execute.

Cursor moving erratically (C)

I'm having some trouble doing a Nim game program. So far I have a program that will show a pyramid of pipes. It looks like the "start position" pyramid on this picture.
http://www.mathsisfun.com/puzzles/images/b-nim.gif
Anyways, I'm having trouble moving around this, whenever I try moving around, my cursor will move in completely erratic ways. Thid will make the game totally unplayable. I'm not sure if it is a problem with my counting variables or even some smaller thing I'm totally missing, anyways here's what I have:
#include <stdlib.h>
int nim()
{
char *tab;
if ((tab = malloc(sizeof(char) * 20 + 4)) == NULL)
return (-1);
tab = " | \n ||| \n ||||| \n |||||||\n"; /* this is indeed a nasty way to do it :P */
putstr(tab);
}
int move_normally()
{
char bffr[10];
int x;
int y;
x = 0;
y = 0;
while (42 && x <= 6 && y <= 3)
{
read(0, bffr, 10);
putstr(tgoto(tgetstr("cm", NULL), x, y);
if (bffr[2] == 66 && y <= 3 && x <= 6)
y++
else if (bffr[2] == 65 && x <= 6 && y <= 3 && (y - 1) >= 0)
y = y - 1;
else if (bffr[2] == 67 && x <= 6 && y <= 3)
x++
else if (bffr[2] == 68 && x <= 6 && y <= 3 && (x - 1) >= 0)
x++
}
}
So, is there something I'm missing here? everything else works almost perfectly and I can't get my hands on why this is giving trouble. Also, are there any other ways to do this? I'm open to any alternative way.

Resources