Your answer is one click away!

cryengineplus February 2016
### C++ Matrix String

I'm comparatively new to stackoverflow, and I'm not sure if I'm permitted to ask these kind of questions. Basically, I have a simple C++ Matrix question in hand and I wanted to understand 2 things out of it,

a) What exactly is being asked to be done here? I'm familiar with basics of matrices and I can do matrix calculations in C++ but I don't really understand the question itself.

b) I'm most definitely not looking for solutions, since I wish to solve this question by myself, on the contrary if someone could point me in the right direction, that would be helpful as well. Thanks!

Question: Given a 3x4 int matrix, output a string that is a valid equation. The sequence starts in the top left corner, and spirals around the matrix in a clockwise fashion. If a valid equation does not exist, output "invalid sequence".

E.g.

```
2 3 5 8
5 2 5 -3
7 0 7 10
```

This should make a sequence of: "2 + 3 = 5 - 8 = -3 + 10 = 7 + 0 = 7 - 5 = 2 - 5 = -3"

Thanks for the help.

The question asks you to travel around a 4x3 matrix in a inward spiraling path verifying that each set of two numbers can be added or subtracted to get the next number in the path - where the first value of each set of two numbers is the result of the previous operation.

If this is the matrix:

```
a b c d
e f g h
i j k l
```

Then the path is:

```
a b c d h l k j i e f g h
```

And the algorithm is:

```
a +- b = c
c +- d = h
h +- l = k
k +- j = i
i +- e = f
f +- g = h
```

If those are all equal then it is a valid sequence. Otherwise you print "invalid sequence"

So you could just make the program into one huge if statement:

```
if( (a + b == c || a - b == c) &&
(c + d == h || c - d == h) &&
(h + l == k || h - l == k) &&
(k + j == i || k - j == i) &&
(i + e == f || i - e == f) &&
(f + g == h || f - g == h) )
{
// print the path
}
else
{
// print "invalid sequence"
}
```

If you do that you don't need any loops or anything.

But like @macroland said, you could convert the 2D matrix to a 1D matrix. How to do this isn't the most obvious thing to do because it isn't as easy as top to bottom, left to right but it is relatively straight forward after you think of a method. The most stright forward way I can think of is to hard code the path taken like this:

```
int a[3][4] = {{ 2, 3, 5, 8 },
{ 5, 2, 5, -3 },
{ 7, 0, 7, 10 }};
int b[13]; // the output array
int x[13] = {0,1,2,3,3,3,2,1,0,0,1,2,3};
int y[13] = {0,0,0,0,1,2,2,2,2,1,1,1,1};
for(int i=0;i<13;i++) b[i]=a[y[i]][x[i]];
```

That of course relies on the fact you know it is always a 4x3 matrix. If you do that you get something equivalent to this:

```
int b[13] = { 2, 3, 5, 8, -3, 10, 7, 0, 7, 5, 2, 5, -3 };
```

Then you can easily make a

Asked in February 2016

Viewed 1,424 times

Voted 9

Answered 1 times

Viewed 1,424 times

Voted 9

Answered 1 times