From 386fa6e8eb5815d036e148578db0eb2c4c93d77d Mon Sep 17 00:00:00 2001 From: Anna Matveev Date: Fri, 19 Jan 2018 14:19:10 +0200 Subject: [PATCH] Update rotateMatrix.js Shorter solution to the rotation problem --- chapter01/1.7 - Rotate Matrix/rotateMatrix.js | 160 ++++++------------ 1 file changed, 52 insertions(+), 108 deletions(-) diff --git a/chapter01/1.7 - Rotate Matrix/rotateMatrix.js b/chapter01/1.7 - Rotate Matrix/rotateMatrix.js index b0e3e28..7244932 100644 --- a/chapter01/1.7 - Rotate Matrix/rotateMatrix.js +++ b/chapter01/1.7 - Rotate Matrix/rotateMatrix.js @@ -1,108 +1,52 @@ -var rotateMatrix = function(matrix) { - var edge = matrix.length - 1; - - var movePixels = function(row, col) { - // starts at m[row][col] - // moves to m[col][edge - row] - var fromRow; - var fromCol; - var fromPixel; - - // first transformation - var toRow = row; // 0 - var toCol = col; // 1 - var toPixel = matrix[row][col]; - - // Do rotational transformation 4 times - for (var i = 0; i < 4; i++) { - fromRow = toRow; - fromCol = toCol; - toRow = fromCol; - toCol = edge - fromRow; - - fromPixel = toPixel; - toPixel = matrix[toRow][toCol]; - matrix[toRow][toCol] = fromPixel; - } - }; - - for (var i = 0; i < matrix.length / 2; i++) { - for (var j = i; j < edge - i; j++) { - console.log(i, j); - movePixels(i, j); - } - } -}; - - -/* TEST */ -var testMatrix = [ -[1, 2, 3, 4], -[0, 1, 2, 3], -[0, 0, 1, 2], -[1, 0, 0, 1] -]; - -console.log('before:'); -console.log(testMatrix[0]); -console.log(testMatrix[1]); -console.log(testMatrix[2]); -console.log(testMatrix[3]); - -rotateMatrix(testMatrix); - -console.log('after:'); -console.log(testMatrix[0]); -console.log(testMatrix[1]); -console.log(testMatrix[2]); -console.log(testMatrix[3]); - -/* -var edge = n - 1; - -pattern observed: -i) col value becomes row value -ii) row value is subtracted off edge and becomes col value - -0100 -0000 -0000 -0000 - -position of 1 -> m[0][1] - -0000 -0001 -0000 -0000 - -position of 1 -> m[1][edge] - -0000 -0000 -0000 -0010 - -position of 1 -> m[edge][edge - 1] - -0000 -0000 -1000 -0000 - -position of 1 -> m[edge-1][0] - -0100 -0000 -0000 -0000 - -position of 1 -> m[0][1] - -flow of iteration: -i) start from top left corner and move diagonally down -ii) for each row, iterate pixels until edge - 1 -(pixel at edge would have been transformed by the first pixel) -iii) at each pixel iteration, iterate through 4 sides -iv) do iteration in place, i.e. store a temp pixel for moving things around -*/ \ No newline at end of file +function rotate(pic) { + let rotatePic = []; + + for (let i=0; i