Find position in an array by position in the array?

Asked

Viewed 253 times

2

If I have an array, ex:

[1, 2, 3, 4, 5, 6, 7, 8, 9]

and I transform this array into an array, e.g.:

           y[0]  y[1]  y[2]

   x[0] =   1  |  2  |  3
           ---------------
   x[1] =   4  |  5  |  6
           ---------------
   x[2] =   7  |  8  |  9

And I have the position of array initial, for example position 5 which in the case is the value -> 6, how do I find the position x, y of the matrix equivalent to the array position, in the case of this example it would be: x:1, y:2.

  • variavel_array[5] -> 6 variavel_array[1,2] -> 6

  • 2

    row = position_no_array / width; column = position_no_array % width (adjust offset for your coordinate system, see how to get the truncation of the division in the chosen language - % is the split rest operator)

  • @Duiliobenjoino, did not understand your comment, just replicated what is in the question?

  • @Interesting Bacco, I’ll try to understand mathematically how you find this and apply it in my code, thanks. If you want to turn it into a reply, I’ll put it back...

  • @matheussoareslacerda I had not understood his doubt. I reli and understood, I believe that Anderson’s response Carlos Woss meets the desired.

1 answer

2


Friend,

To get the position just split take the value subtract by 1 and divide by the number of rows or columns (if it is a perfect matrix) the position x will be the integer value of the division and the rest will be y Example:

(5-1)/3 = 1 and the rest is 2 in this case the array will be array [x,y] [1,1]

(6-1)/3 = 1 and the rest is 2 in this case the array will be array [x,y] [1,2]

Browser other questions tagged

You are not signed in. Login or sign up in order to post.