Search code examples
c#mathcartesian-coordinates

Find the index in a single array of a Cartesian coordinate


I'm trying to figure out something that should be very simple yet, for some reason I just can't find the answer. I've been trying out formulas for the past few hours now. Take a Cartesian coordinate system of a grid 10 by 10 so 0,0 to 10,10. Each coordinate has a float assigned to it (determining height) and they have been read into a float[] row by row first row (0,0) to (10,0) second row (0,1) to (10,1). Now I want to write a helper method, to fetch the height of a certain Cartesian coordinate fe: (10, 0). That float would reside at index 9 in the float[] and (0, 1) would reside at index 10. I've tried several attempts but each time (0, 0) is being a stubborn mule. Here are some of the formulas I tried.

Z = (Y * 10 + X) 
  works for 0, 0 but not really for 10, 0 cause that index should be 9
Z = ((Y * 10 + X) - 1) 
  works for 10, 0 but well not for 0, 0

I tried a few more complicated once but can't recall them now since my notepad where I wrote them down has closed without saving. I would appreciate if someone can put me in the right direction, but please use simple math explanations.


Solution

  • If your grid is 10 by 10, then it's from (0,0) to (9,9). A row from (0,0) to (10,0) means 11 items in a row, so your function should be:

    Z = (Y * 11 + X)