हमें एक JavaScript फ़ंक्शन लिखना है जो n * n क्रम की सरणियों की एक सरणी (वर्ग मैट्रिक्स) लेता है। फ़ंक्शन को सरणी को 90 डिग्री (घड़ी की दिशा में) घुमाना चाहिए। शर्त यह है कि हमें इसे स्थानांतरित (in-place) करना है (कोई अतिरिक्त सरणी आवंटित किए बिना)।
उदाहरण के लिए -
यदि इनपुट सरणी है -
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 ] ]