0

Sorry if this is a dumb question but I couldn't figure out the math formula.

I need to map number 1 to 9 to a 2D array/matrix with the position numbers like this:

123
456
789

So 1 -> M[0][0], 2 -> M[0][1] and so on.

Then what if the positions are labelled like this? The indices start from 0, not from 1.

012
345
678

The formula needs to work for larger matrix size input: 4x4, 4x5, 3x6, etc.

I'm completely lost.

I found some answers about Map a 2D array onto a 1D array but they're not quite what I'm looking for. I feel like I should be able to build on top of that but I couldn't figure it out.

Viet
  • 6,513
  • 12
  • 42
  • 74
  • Just add 1 to the index, i.e. `M[i][j] = i * cols + j + 1` where `cols` is the number of columns – meowgoesthedog May 28 '22 at 16:43
  • Hi. Thank you for the suggestion. That is the opposite way. You have i and j and map it to a flat array index. I need to find i and j from the the flat array index. – Viet May 29 '22 at 17:41

0 Answers0