You are viewing a single comment's thread. Return to all comments →
Javascript - array manipulation
function matrixRotation(matrix, r) { let lengthRows = matrix.length -1, lengthCols = matrix[0].length - 1 let startRow = 0, startCol = 0 while(lengthRows > 0 && lengthCols > 0) { const aroundLength = (lengthRows * 2) + (lengthCols * 2) const endRow = lengthRows + startRow, endCol = lengthCols + startCol let row = startRow, col = startCol const indexes = {} for (let i = 0; i < aroundLength; i++) { indexes[i] = [row, col] if (row === startRow && col < endCol) col++ else if (col === endCol && row < endRow) row++ else if (row === endRow && col > startCol) col-- else row-- } const tempArray = Object.keys(indexes).reduce((arr, key) => { const [row, col] = indexes[key] arr.push(matrix[row][col]) return arr }, []) const rest = r % aroundLength const rotatedElements = tempArray.splice(0, rest) tempArray.push(...rotatedElements) Object.keys(indexes).forEach((key, i) => { const [row, col] = indexes[key] matrix[row][col] = tempArray[i] }) startRow++; startCol++; lengthRows -= 2; lengthCols -= 2 } matrix.forEach((value) => console.log(...value)); }
Seems like cookies are disabled on this browser, please enable them to open this website
Matrix Layer Rotation
You are viewing a single comment's thread. Return to all comments →
Javascript - array manipulation