Flattening a Rectangular Grid by Rows

A rectangular grid stored row by row can translate coordinates into one-dimensional offsets if its width is fixed.

Source
Anbloq
Language
English
Created
Updated
Chapters
4
Reading time
1 min
In this article4 chapters
  1. Derive the position
  2. Invert an offset
  3. Construct a grid whose orientation is visible
  4. Keep dimensions alongside a serialized buffer

Derive the position

For width \(w\), the linear offset for row \(r\) and column \(c\) is \(rw+c\). On a grid of width three, row one column two becomes offset five. The derivation counts one complete row before the final column, following row and column indices.

Invert an offset

At width three, offset seven has quotient two and remainder one, so it is row two column one. Validate a positive width and valid offset first. Quotient and remainder explain why this recovers both coordinates.[1]

Construct a grid whose orientation is visible

Take two rows [A, B, C] and [D, E, F]. Row-major flattening yields [A, B, C, D, E, F]. A column-major traversal yields [A, D, B, E, C, F]. Both contain the same values and length, so comparing sets cannot detect an orientation mistake. Test values at known coordinates, especially (one, zero), because it differs between the two layouts. See row and column indices.

Keep dimensions alongside a serialized buffer

Six values can form one row of six, two by three, or three by two. Recovering the original grid requires the intended dimensions and storage order. Validate that the stated dimensions multiply to the buffer length, and define whether zero extents are supported. A single trailing value should cause a shape error where a complete grid is required. If chunks merely reflect available input, preserve each row length instead. See flattening ragged sequences.

References

  1. Python Software Foundation, Python Standard Library: Built-in Types ↩