1

The title might be a bit confusing, since I didn't know how to put this into one sentence.

I have a 10x10 grid and every square on the grid is 100 pixels (this is a programming problem) from edge to edge. If I have a position where the x and y-value represent pixels away from the top or left side of the grid, how can I determine which square on the grid contains the position?

David K
  • 98,388
JensB
  • 113

1 Answers1

1

The simplest method would be to use the ceiling function: that is, $\lceil x \rceil$ is the smallest integer which is not smaller than $x$. So, supposing the squares are numbered $1$ to $10$, a pair of coordinates $(x,y)$ becomes $(\lceil \frac{x}{100} \rceil , \lceil \frac{y}{100}\rceil )$ - telling us the "square" coordinates. Take, for example, $(153, 814)$. Then the corresponding square is $(\lceil 1.53\rceil,\lceil 8.14 \rceil ) = (2, 9)$, i.e. the square that is second from the left and 9th from the bottom (alternatively, second from the top).

Chubby Chef
  • 1,524
  • Thanks for the help! Also, what would the equation look like if there was another variable that represented the number of pixels between the edge of the screen and the grid? – JensB Oct 29 '20 at 23:13
  • @JensB Can you clarify please? Actually, what I suggested isn't strictly speaking an equation, but rather a function: namely, $f((x,y)) = (\lceil \frac{x}{100}\rceil , \lceil \frac{y}{100}\rceil )$. If you just wish to shift the origin, there is no need to introduce a new variable - simply subtract whatever difference there is to shift the origin back to its place at the bottom left of the grid (or wherever you need it to be). – Chubby Chef Oct 29 '20 at 23:35
  • Yeah, that did it. I tried that yesterday before I went to bed but it didn't work, so I posted that comment. Turns out I was calculating the y-value using my x-value. I fixed it and now it works perfectly. Thanks for the help! – JensB Oct 30 '20 at 10:00
  • @JensB no problem, glad it works now :) – Chubby Chef Oct 30 '20 at 10:02