Traverse rows issue

Hello,

I have the following 2 functions that I use to move the numbers from an array for a 2048 game.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
void goUp()
{

	for (int j = 0; j < 4; j++) //traverse the columns
	{
		for (int i = 3; i >= 0; i--) //traverse the rows - start going through the array from the bottom
		{
			for (int k = 0; k < 4; k++)  //loop purpose: check the same column several times to see if all the swaps were done
			{
				if (nums[i - 1][j] == 0)
				{
					nums[i - 1][j] = nums[i][j];
					nums[i][j] = 0;
				}
				else if (nums[i - 1][j] == nums[i][j])
				{
					nums[i - 1][j] *= 2;
					nums[i][j] = 0;
				}
			}
		}
	}
}

void goDown()
{
	for (int j = 0; j < 4; j++)
	{
		for (int i = 0; i < 4; i++)  //traverse the rows from the top
		{
			for (int k = 0; k < 4; k++) // loop to check that all swaps were done
			{
				if (nums[i][j] == 0)
				{
					nums[i + 1][j] = nums[i][j];
					nums[i][j] = 0;
				}
				else if (nums[i + 1][j] == nums[i][j])
				{
					nums[i + 1][j] *= 2;
					nums[i][j] = 0;
				}
			}	
		}
	}
}


The goUp() functions works as intended, but the second function doesn't seem to work at all.
Neither works correctly.

You have for (int i = 3; i >= 0; i--), so lets consider the last iteration, where i == 0
The nums[i - 1][j] == 0
is therefore nums[ -1 ][j] == 0

There is no row -1.

The other function has similar out-of-range error.
Adding another check if (i > 0) will result in a weird behavior. The numbers will move in random directions.
I do not know the "2048 game", so can you explain the logical goal of the "goUp" function?

You seem to operate on 4x4 matrix. The goUp seems to repeat same operation for each column in it. Therefore, given one array of four values (one column from your matrix), what should the goUp() do to that one array?

What values does an array have? For example, if the array has {a, b, c, d}, what does it have after goUp?



PS. Your nums seems to be a global variable. You could pass the array to the functions as argument, removing the need for global variable.

PS2. You have literal value 4 in several places. Could the use of a named constant in all those places make maintenance of the code easier?
I just wnated to point out one thing, the range of i is 0-3, if you are subtracting 1 from i, while you are subtracting 1 from 0 you're out of the array bound, and compiler will not complain but when you run the program you will find garbage value.
what you can do is assign num [i]=num[i+1]
if the size of array is 4 the thinking the value i as current index is enough
its for go up funciton
Topic archived. No new replies allowed.