Reputation: 5021
Given a number say 3 to 4 , I need to generate a 2D array in spiral form and print it. For Example :
If given 3, the 3*3 array generated can be printed like:
7 8 9
6 5 4
1 2 3
Or, given 4, it should be 4*4 array in spiral form
16 15 14 13
9 10 11 12
8 7 6 5
1 2 3 4
I tried in a psudeo code to push all the numbers in a one single dimensional array.
But I do not how to print them in such a 2D array format.
PSEUDO _ CODE
arr = new Array(val*val);// []
let pass = 0;
let j = 0;
target = val*val; // 9
while(pass < n) {
if(pass % 2 === 0) { //pass 0 - 1 2 3 // pass 2 - 7 8 9
for(let i = j + 1; i >= j+n; i++) {
arr.push(i);
}
j = i;
} else { // pass 1 - 6 5 4
for(let i = j+n; i >= j+1; i--) {
arr.push(i);
}
j = i;
}
pass++;
}
Upvotes: 0
Views: 156
Reputation: 2829
You can do it like this
function a(b) {
var c = "";
for(var d = b * b;d > 0; d--) {
c += d + ((d - 1) % b === 0 ? "\n" : " ");
}
return c;
}
console.log(a(2));
console.log(a(3));
console.log(a(4));
console.log(a(5));
Upvotes: 0
Reputation: 386604
You could calculate the value for a certain position.
const
getZigZag = length => Array.from(
{ length },
(_, i) => Array.from(
{ length },
(_, j) => (length - i) % 2
? (length - i - 1) * length + j + 1
: (length - i - 1) * length + length - j
)
);
getZigZag(3).forEach(a => console.log(...a));
console.log()
getZigZag(4).forEach(a => console.log(...a));
Upvotes: 1
Reputation: 22534
This could be done using Array.from
. First for each row generate number and then join them. The inner array could be joined on ' '
, while the outer array could be joined using '\n'
after reversing.
const generatePattern = (length) => Array.from({length}, (_, i) => {
const subArray = Array.from({length}, (_, index) => length*i + index + 1);
return i % 2 === 0 ? subArray.join(' ') : subArray.reverse().join(' ');
}).reverse().join('\n');
console.log(generatePattern(3));
console.log(generatePattern(4));
console.log(generatePattern(5));
.as-console-wrapper { max-height: 100% !important; top: 0; }
Upvotes: 1