shampa - 4 months ago 24

C Question

I am working on my data in a C/C++ program, which is 2 dimensional. Here my value is calculated for pair-wise and here values would be same for

`foo[i][j]`

`foo[j][i]`

Thus if I implement it by using a simple 2 dimensional array, half of my space would be wasted. So what would be best data structure to represent this lower/upper triangular matrix.

Regards,

Answer

Really, you're best off just using a regular two dimensional matrix. RAM is pretty cheap. If you really don't want to do that, then you can build a one-dimensional array with the right number of elements and then figure out how to access each element. For example, if the array is structured like this:

```
j
1234
i 1 A
2 BC
3 DEF
4 GHIJ
```

and you have it stored as a one dimensional array, left to right, you'd access element `C`

`(2, 2)`

with `array[3]`

. You can work out a function to go from `[i][j]`

to `[n]`

but I won't spoil your fun. But you don't have to do this unless the triangular array in question is really huge or you're very concerned about space.