เราจำเป็นต้องเขียนฟังก์ชัน JavaScript ที่รับอาร์เรย์ของอาร์เรย์ n * n ลำดับ (เมทริกซ์สี่เหลี่ยม) ฟังก์ชันควรหมุนอาร์เรย์ 90 องศา (ตามเข็มนาฬิกา) เงื่อนไขคือเราต้องทำสิ่งนี้แทน (โดยไม่ต้องจัดสรรอาร์เรย์พิเศษใดๆ)
ตัวอย่างเช่น −
หากอาร์เรย์อินพุตเป็น −
const arr = [ [1, 2, 3], [4, 5, 6], [7, 8, 9] ];
จากนั้นอาร์เรย์ที่หมุนควรมีลักษณะดังนี้ -
const output = [ [7, 4, 1], [8, 5, 2], [9, 6, 3], ];
ตัวอย่าง
ต่อไปนี้เป็นรหัส -
const arr = [
[1, 2, 3],
[4, 5, 6],
[7, 8, 9]
];
const rotateArray = (arr = []) => {
for (let rowIndex = 0; rowIndex < arr.length; rowIndex += 1) {
for (let columnIndex = rowIndex + 1; columnIndex < arr.length;
columnIndex += 1) {
[
arr[columnIndex][rowIndex],
arr[rowIndex][columnIndex],
] = [
arr[rowIndex][columnIndex],
arr[columnIndex][rowIndex],
];
}
}
for (let rowIndex = 0; rowIndex < arr.length; rowIndex += 1) {
for (let columnIndex = 0; columnIndex < arr.length / 2;
columnIndex += 1) {
[
arr[rowIndex][arr.length - columnIndex - 1],
arr[rowIndex][columnIndex],
] = [
arr[rowIndex][columnIndex],
arr[rowIndex][arr.length - columnIndex - 1],
];
}
}
};
rotateArray(arr);
console.log(arr); ผลลัพธ์
ต่อไปนี้เป็นผลลัพธ์บนคอนโซล -
[ [ 7, 4, 1 ], [ 8, 5, 2 ], [ 9, 6, 3 ] ]