0

I'm looking for the shortest equation to find the flattened position of an ordered pair.

Let's use a TicTacToe board for example.

|---|---|---|
| 0 | 1 | 2 |
|---|---|---|
| 3 | 4 | 5 |
|---|---|---|
| 6 | 7 | 8 |
|---|---|---|

Given (1, 1), how can I get 4? What about (2, 1) to get 5?

I would like the solution to be general and not language syntax-specific.

Jacob Birkett
  • 1,927
  • 3
  • 24
  • 49

1 Answers1

1

Since you're numbering along rows first, the formula you need is row_number * column_count + column_number.

If you were numbering down columns first, or right-to-left, or any other variation, you would have to adjust that formula accordingly.

Keep in mind, also, that this works for zero-based indexing only.

David Z
  • 128,184
  • 27
  • 255
  • 279