ภาพรวม
Transpose ของเมทริกซ์ (อาร์เรย์ 2 มิติ) คือการสลับแถวกับคอลัมน์ กลายเป็นเมทริกซ์ใหม่ที่แถวเดิมกลายเป็นคอลัมน์ และคอลัมน์เดิมกลายเป็นแถว
การนำไปใช้ (In-place สำหรับเมทริกซ์สี่เหลี่ยมจัตุรัส)
const arr = [
[1, 1, 1],
[2, 2, 2],
[3, 3, 3]
];
const transpose = (arr) => {
for (let i = 0; i < arr.length; i++) {
for (let j = 0; j < i; j++) {
// สลับค่า arr[i][j] กับ arr[j][i]
const tmp = arr[i][j];
arr[i][j] = arr[j][i];
arr[j][i] = tmp;
}
}
};
transpose(arr);
console.log(arr);
ผลลัพธ์
[ [ 1, 2, 3 ], [ 1, 2, 3 ], [ 1, 2, 3 ] ]
เวอร์ชันสำหรับเมทริกซ์ไม่ใช่สี่เหลี่ยมจัตุรัส (Rectangular Matrix)
const transposeRectangular = (matrix) => {
if (matrix.length === 0) return [];
const rows = matrix.length;
const cols = matrix[0].length;
const result = Array.from({ length: cols }, () => Array(rows).fill(0));
for (let i = 0; i < rows; i++) {
for (let j = 0; j < cols; j++) {
result[j][i] = matrix[i][j];
}
}
return result;
};
// ตัวอย่าง
const rect = [
[1, 2, 3],
[4, 5, 6]
];
console.log(transposeRectangular(rect));
// [ [1, 4], [2, 5], [3, 6] ]
วิธีสั้นๆ ด้วย ES6
const transposeES6 = (matrix) =>
matrix[0].map((_, colIndex) => matrix.map(row => row[colIndex]));
การประยุกต์ใช้
- การประมวลผลภาพ (Image Processing)
- พีชคณิตเส้น (Linear Algebra)
- การจัดการข้อมูลตาราง (Data Table Manipulation)
- Machine Learning (Feature Transformation)
ข้อควรระวัง
วิธี In-place (โค้ดตัวอย่างแรก) ใช้ได้เฉพาะเมทริกซ์สี่เหลี่ยมจัตุรัส (N×N) เท่านั้น สำหรับเมทริกซ์ M×N ต้องสร้างอาร์เรย์ใหม่