codebuddies / DailyAlgorithms

Do a problem. Create (or find) your problem in the issues. Paste a link to your solution. See others' solutions of the same problem.
12 stars 1 forks source link

[Cracking The Coding Interview] 1.7: Rotate Matrix #8

Open jtkaufman737 opened 5 years ago

jtkaufman737 commented 5 years ago

Given an image represented by an NxN matrix, where each pixel in the image is 4 bytes, write a method to rotate the image by 90 degrees. Can you do this in place?

jtkaufman737 commented 5 years ago
let array = [
  [0,1,2,3],
  [0,1,2,3],
  [0,1,2,3],
  [0,1,2,3]
]

let array2 = [
  ['a','a','a','a','a'],
  ['b','b','b','b','b'],
  ['c','c','c','c','b'],
  ['d','d','d','d','d'],
  ['e','e','e','e','e']
]

function pixelPerfect(arr) {
  let result = [];

  for(let i = 0; i < arr.length; i++) {
    result.push([]); // probably a clever way to wrap this into the other loop...
  }

  for(let i=0; i < arr.length; i++) {
    for(let j = arr.length - 1; j >= 0; j --) {
      result[j][i] = arr[i][j];
    }
  }

  console.log(arr);
  console.log(result);
}

pixelPerfect(array);
pixelPerfect(array2);
lpatmo commented 5 years ago

https://repl.it/@lpatmo/QuizzicalCoarseResource

function createMatrix(n) {
  let newMatrix = []
  for (let row = 0; row < n; row++) {
      newMatrix.push([])
    for (let column = 0; column < n; column++) { 
    }
  }
  console.log('new matrix:', newMatrix)
  return newMatrix;
}

function rotateMatrix(matrix) {
  //find the n of the matrix
  let n = matrix.length;
  let rotated = createMatrix(n);
  for (let i = n-1; i >= 0; i-- ) {
     for (let j = 0; j < n; j++) {
       console.log(i, j)
       rotated[j].push(matrix[i][j])
     }
  }
  console.log('rotated:', rotated) 
}
console.log(rotateMatrix([[1,2,3],[4,5,6],[7,8,9]]))