ম্যাট্রিক্স ট্রান্সপোজ মানে রো এবং কলাম একে অপরের সাথে বদলানো।
উদাহরণ
মূল ম্যাট্রিক্স (3×3): [1, 1, 1] [2, 2, 2] [3, 3, 3] ট্রান্সপোজ: [1, 2, 3] [1, 2, 3] [1, 2, 3]
ইন-প্লেস ট্রান্সপোজ (স্কয়ার ম্যাট্রিক্স)
const transposeInPlace = (matrix) => {
const n = matrix.length;
// শুধু উপরের ট্রায়্যাঙ্গুলার পার্টে লুপ
for (let i = 0; i < n; i++) {
for (let j = 0; j < i; j++) {
// সিম্পল
[matrix[i][j], matrix[j][i]] = [matrix[j][i], matrix[i][j]];
}
}
return matrix;
};
// টেস্ট
const arr = [
[1, 1, 1],
[2, 2, 2],
[3, 3, 3]
];
transposeInPlace(arr);
console.log(arr);
// [ [1, 2, 3], [1, 2, 3], [1, 2, 3] ]
নন-স্কয়ার ম্যাট্রিক্সের জন্য (নতুন অ্যারে তৈরি)
const transpose = (matrix) => {
if (!matrix.length) return [];
const rows = matrix.length;
const cols = matrix[0].length;
// নতুন ম্যাট্রিক্স তৈরি (cols × rows)
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 rectMatrix = [
[1, 2, 3],
[4, 5, 6]
]; // 2×3
console.log(transpose(rectMatrix));
// [ [1, 4], [2, 5], [3, 6] ] // 3×2
ফাংশনাল পদ্ধতি
const transposeFP = (matrix) => matrix[0].map((_, colIndex) => matrix.map(row => row[colIndex]));
উৎপাদন
[ [ 1, 2, 3 ], [ 1, 2, 3 ], [ 1, 2, 3 ] ]