Prep: Rotate Matrix

Prep algorithm

by bladnman

HTML

<input type=button id="theButton" value="run test" class="runButton">

<div id="log" class="log"></div>

CSS

.runButton {
    width:   125px;
    margin:  20px;
}
.log {
   padding:10px; 
    margin: 20px; 
    border: 1px dotted #ccc; 
    color:#888; 
    font-face: arial; 
    font-size:12px; 
    background: #fbfbfb; 
}

JavaScript

/* ************************************ */
function runTest() {
    var origMap = [
        [1,2,3,4,20],
        [5,6,7,8,21],
        [9,10,11,12,22]
    ];
    
    logMap(origMap, "Orig Map");
    logMap(getRotatedClockwise(origMap), "Clock Rotated Map");
    logMap(getRotatedCounterwise(origMap), "Counter Rotated Map");
}
function getRotatedClockwise(origMap) {
    
    var newMap, w, h, col, row, newCol, newRow;
    newMap = [];
    w = origMap.length;
    h = origMap[0].length;
    
    var totalRows = origMap.length;
    var totalCols = origMap[0].length
    
    // clockwise means:
    //    newCol     = inverse of oldrow
    //    newRow     = oldcol
    
    // work from bottom-row-up
    for (row = origMap.length - 1; row >= 0; row--) {
        var colCells = origMap[row];

        // work each column-cell left-to-right
        for (col = 0; col < colCells.length; col++) {
            var cellVal = colCells[col];
            
            newRow = col;
            newCol = totalRows - row - 1;
            
            // map to new map
            if (typeof newMap[newRow] == "undefined") {
                newMap[newRow] = [];
            }
            newMap[newRow][newCol] = cellVal;
            //console.log("putting ["+cellVal+"] at:", newCol, newRow, newMap[newRow][newCol]);

        }
        
        //console.log(newMap);
    }
    
    return newMap;
}

function getRotatedCounterwise(origMap) {
    
    var newMap, w, h, x, y, newX, newY;
    newMap = [];
    w = origMap.length;
    h = origMap[0].length;
    
    // step cols
    for (x = 0; x < w; x++ ) {
        var col = origMap[x];

        newY     = x;
        
        // step rows (cells)
        for (y = 0; y < h; y++ ) {
            var val = col[y];
        
            // get newX
            newX     = h - y - 1;
         
            // map to new map
            if (typeof newMap[newX] == "undefined") {
                newMap[newX] = [];
            }
           ...