1
$\begingroup$

Given a flat array of values as such, representing a Sudoku board:

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

As well as knowing the amount of rows & columns, such as 9 x 9

How do I convert an index for any point on the array into an x and y coordinate as if it were a 9x9 grid?

For example, when provided with rows & columns 9x9 and index 10 should yield x: 2, y: 2 and 80 should yield x: 9, y: 9

$\endgroup$
2
  • $\begingroup$ Isn't that a programming question ? $\endgroup$ – Captain Lama Mar 29 '16 at 9:34
  • $\begingroup$ It's to be implemented in such, yes, but I felt solving the problem itself is something I would need mathematical intervention for. $\endgroup$ – toficofi Mar 29 '16 at 9:38
5
$\begingroup$

You use division and modulo. Given index 10, you have $x=10/9$ and $y=10\%9$ (using programming syntax). This is using an index that starts at 0. If you want to start at one, then just add one to each of these.

$\endgroup$
3
  • $\begingroup$ Is it not the other way around? Modulo determines the $x$ coordinate and integer division the $y$ coordinate? $\endgroup$ – Markus Amalthea Magnuson Apr 18 at 18:06
  • 1
    $\begingroup$ Good question, but it depends on if $x$ and $y$ are intended to be the row and column, or the $x$ and $y$ directions as if looking at a graph. Often, the first number is the row, and the second is the column. Interestingly, the examples in the original question are ambiguous! They gave 2,2 and 9,9 for the examples, so we can't disambiguate from the question. $\endgroup$ – Carser Apr 18 at 18:28
  • $\begingroup$ You're absolutely right :) $\endgroup$ – Markus Amalthea Magnuson Apr 18 at 18:36
0
$\begingroup$

Use double arrays. In programming languages this is often represented by: a[][]

Then you can define a[1][1] etc.

$\endgroup$
2
  • 1
    $\begingroup$ The source data is only a flat array. I cannot turn it into a double array until first figuring out this. $\endgroup$ – toficofi Mar 29 '16 at 9:41
  • 1
    $\begingroup$ I'm not sure but he is probably constrained to use a 1d array. It's surprisingly common to see multidimensional arrays implemented like this. Perhaps it's a historical thing, where some older languages didn't have the multidimensional syntax a[][]. $\endgroup$ – Carser Mar 29 '16 at 9:42

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.