แนวคิด
การแปลงอาร์เรย์ 2 มิติ (n×m) เป็น 1 มิติ ขนาดของอาร์เรย์ 1 มิติ = n×m มี 2 วิธีการจัดเก็บ:
1. Row Major Order
เก็บแถวละแถว ตัวแปร (i,j) ในอาร์เรย์ 2 มิติ จะอยู่ที่ index = j + i×m ในอาร์เรย์ 1 มิติ
2. Column Major Order
เก็บคอลัมน์ละคอลัมน์ ตัวแปร (i,j) จะอยู่ที่ index = i + j×n
ตัวอย่าง
n=3, m=5, (i,j)=(0,2)
- Row-major index = 2 + 0×5 = 2
- Column-major index = 0 + 2×3 = 6
โปรแกรมตัวอย่าง
#include <iostream>
using namespace std;
int main() {
int n = 3, m = 5;
int grid[3][5] = {{1,2,3,4,5}, {6,7,8,9,10}, {11,12,13,14,15}};
int i = 0, j = 2;
int rowMajorIndex = i * m + j;
cout << "Row-major index of (0,2): " << rowMajorIndex << endl;
int colMajorIndex = i + j * n;
cout << "Column-major index of (0,2): " << colMajorIndex << endl;
return 0;
}
ผลลัพธ์
Row-major index of (0,2): 2 Column-major index of (0,2): 6