Luca Sepe

Storing 2D arrays in linear storage (1D array)

Math Coding

The 2D array:

Matrix

could be stored in two possible ways:

Index Row-Major Order Row-Minor Order
0 a11 a11
1 a12 a21
2 a13 a12
3 a21 a22
4 a22 a13
5 a23 a23

Row-Major Order

The offset in the linear representation of the element given at row and col position is:

offset := row * nrOfCols + col

Try It!

func TestRowMajorOrder(t *testing.T) {
	array := []string{"a11", "a12", "a13", "a21", "a22", "a23"}
	nrOfCols := 3

	tests := []struct {
		row, col int
		want     string
	}{
		{1, 1, "a22"},
		{0, 2, "a13"},
		{0, 0, "a11"},
	}

	for _, tt := range tests {
		t.Run(fmt.Sprintf("@(%d,%d)", tt.row, tt.col), func(t *testing.T) {
			// Element Index
			offset := tt.row*nrOfCols + tt.col
			got := array[offset]
			if got != tt.want {
				t.Errorf("got [%v] want [%v]", got, tt.want)
			}
		})
	}
}

Column-Major Order

The offset of an element in column-major layout can be found using this equation:

offset := col * nrOfRows + row

Try It!

func TestColumnMajorOrder(t *testing.T) {
	array := []string{"a11", "a21", "a12", "a22", "a13", "a23"}
	nrOfRows := 2

	tests := []struct {
		row, col int
		want     string
	}{
		{1, 1, "a22"},
		{0, 2, "a13"},
		{0, 0, "a11"},
	}

	for _, tt := range tests {
		t.Run(fmt.Sprintf("@(%d,%d)", tt.row, tt.col), func(t *testing.T) {
			// Element Index
			offset := tt.col*nrOfRows + tt.row
			got := array[offset]
			if got != tt.want {
				t.Errorf("got [%v] want [%v]", got, tt.want)
			}
		})
	}
}