Getting Grid Coordinates From Number

I haven't really written about a topic like this before, so this is completely unexplored territory for me. We will see how it goes.

I have recently been working on this new project that uses this grid system in some pretty interesting ways. I had a table something like the following table.

Table1

I was working on building a function that would take in the width and height of the table, along with the number (ex. 27) and would have to output the coordinates. So for example in the case of 27 it would have to output the X coordinate of 3 and the Y coordinate of 5. I had to build another function that would do the same but in reverse. So it would take in the coordinates and output the number.

Before you continue reading, if you are interested in trying it yourself before I give the solution feel free to checkout the Codewars Kata I made.

Normally having a graph like the following would be much easier to find the solution.

Table2

At that point you could just multiply the coordinates together to get the given solution. To find the coordinates it would require a lot more effort, and especially since there are duplicate numbers there is no way to be 100% confident that your solution is the only unique one.

In order to get the X coordinate you can just take given number and take the remainder of number / width. If that number is zero that means that it should be the width. To get the Y coordinate you can take the number / width and instead of taking the remainder of that you can just round it up the nearest whole number.

For example in JavaScript this would look something like the following.

{
	x: number % width || width,
	y: Math.ceil(number / width)
}

In order to take the coordinates and convert it into the item number you can use do the following.

((y - 1) * width) + x

This will return the given number for the given coordinates.

This whole system took me a while to perfect and wrap my head around. It's one of those things that makes perfect sense when you find the solution but it can sometimes take a lot of effort to come up with the correct math to get it to work.