Transpose คือการสลับแถวกับคอลัมน์ของเมทริกซ์ (2D Array) แถวกลายเป็นคอลัมน์ คอลัมน์กลายเป็นแถว
ตัวอย่าง
Input: Output: [1, 1, 1] [1, 2, 3] [2, 2, 2] → [1, 2, 3] [3, 3, 3] [1, 2, 3]
ตัวอย่างโค้ด (In-place สำหรับ Square Matrix)
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]] = [arr[j][i], arr[i][j]];
}
}
};
transpose(arr);
console.log(arr);
ผลลัพธ์
[ [1, 2, 3], [1, 2, 3], [1, 2, 3] ]
เวอร์ชันสำหรับ Non-Square Matrix (สร้างใหม่)
const transpose = matrix => matrix[0].map((_, colIndex) => matrix.map(row => row[colIndex])); const rect = [ [1, 2, 3], [4, 5, 6] ]; // 2x3 → 3x2 console.log(transpose(rect)); // [ [1, 4], [2, 5], [3, 6] ]
In-place ใช้ได้เฉพาะ Square Matrix (n×n) ส่วน Rectangular ต้องสร้างอาร์เรย์ใหม่