Click here to Skip to main content
15,881,852 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Some reason I am getting results of:

[1,2,3,6,9,8,7,1,5]


Instead of:
[1,2,3,6,9,8,7,4,5]


What I have tried:

function spiralOrder(matrix) {
  // your code here...
  let top = 0;
  let left = 0;
  let bot = matrix.length - 1;
  let right = matrix[0].length-1;
  const results = [];
  const size = matrix.length * matrix[0].length;
  
  while (results.length < size) {
      
    for (let i = left; i <= right && results.length < size; i++) {
        results.push(matrix[top][i]);
    } 
    top++;
    
    for (let i = top; i <= bot && results.length < size; i++) {
        results.push(matrix[i][right]);
    } 
    right--;
    
    for (let i = right; i >= left && results.length < size; i--) {
        results.push(matrix[bot][i]);
    }
    bot--;

    for (let i = bot; i >= top && results.length < size; i--) {
        results.push([i][left]);
    }
    left++;

  }
    return results;
};


matrix = [[ 1, 2, 3],
          [ 4, 5, 6],
          [ 7, 8, 9]]

console.log(spiralOrder(matrix)); // [1,2,3,6,9,8,7,4,5]

matrix = [[1, 2, 3, 4],
          [5, 6, 7, 8],
          [9,10,11,12]]


console.log(spiralOrder(matrix)); // [1,2,3,4,8,12,11,10,9,5,6,7]
Posted
Updated 1-Oct-22 23:48pm

1 solution

JavaScript
results.push([i][left]);

Did you forget the matrix in this line?
 
Share this answer
 
Comments
Chris Aug2022 2-Oct-22 6:43am    
Thank you Griff. <3 You're too good to me, haha.
I really should go to sleep when I get very tired instead of continuing. It's 6:43am now.
But if I keep up this pace I should be done studying and be able to get a job in about a month or month 1/2 and not be homeless anymore. XD Must keep moving forward!
Thanks again.
OriginalGriff 2-Oct-22 6:50am    
We all do it: I read what I meant to write ... :D

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900