Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- function myFunc(rows, cols) {
- maxNum = rows * cols;
- let field = new Array(rows);
- for (let i = 0; i < rows; i++) field[i] = new Array(cols);
- let numsArr = [];
- for (let i = 1; i <= maxNum; i++) {
- numsArr.push(i);
- }
- let topRow = 0,
- leftCol = 0,
- rightCol = cols - 1,
- bottomRow = rows - 1;
- let idx = 0;
- while (true) {
- // top row
- for (let c = leftCol; c <= rightCol; c++) {
- field[topRow][c] = numsArr[idx];
- idx++;
- }
- topRow++;
- if (topRow > bottomRow) {
- break;
- }
- // right col
- for (let r = topRow; r <= bottomRow; r++) {
- field[r][rightCol] = numsArr[idx];
- idx++;
- }
- rightCol--;
- if (rightCol < leftCol) {
- break;
- }
- // bottomRow
- for (let c = rightCol; c >= leftCol; c--) {
- field[bottomRow][c] = numsArr[idx];
- idx++;
- }
- bottomRow--;
- if (bottomRow < topRow) {
- break;
- }
- // leftCol
- for (let r = bottomRow; r >= topRow; r--) {
- field[r][leftCol] = numsArr[idx];
- idx++;
- }
- leftCol++;
- if (leftCol > rightCol) {
- break;
- }
- }
- for (let i = 0; i < field.length; i++) {
- console.log(field[i].join(" "));
- }
- }
- myFunc(5, 5);
Advertisement
Add Comment
Please, Sign In to add comment