Problem of the Day
A new programming or logic puzzle every Mon-Fri

Matrix Rotation

The bank manager at my local bank recently gave me the algorithm to access the bank's vault. I thought I'd pass on the algorithm to you all for "safe keeping". Basically the vault has a USB port which you'll need to plug in to. Once plugged in the vault will send you an NxN matrix such as the one below.

Monday-Friday the key to the vault is to rotate the matrix 90 degrees clockwise. On Saturday and Sunday you have to rotate the matrix 90 degrees counter-clockwise. My dog accidentally got locked in the vault and the bank manager is no where to be found. Can someone help me write a program to get him out?

matrix=[[1,2,3,4,5],
        [6,7,8,9,10],
        [11,12,13,14,15],
        [16,17,18,19,20],
        [21,22,23,24,25]]

#Rotated 90 degrees clockwise
matrix=[[21, 16, 11, 6, 1], 
        [22, 17, 12, 7, 2],
        [23, 18, 13, 8, 3],
        [24, 19, 14, 9, 4],
        [25, 20, 15, 10, 5]]

Bonus points for fewer characters of code.

Permalink: http://problemotd.com/problem/matrix-rotation/

Comments:

  • Ori - 10 years, 9 months ago

    python from datetime import date print [list(reversed(q)) for q in zip(*matrix)] if date.today().weekday() < 5 else zip(*(reversed(q) for q in matrix))

    reply permalink

  • Anonymous - 10 years, 9 months ago

    This gives you the right answer, not sure if it counts as rotating it 90 degrees.

    matrix=[[1,2,3,4,5], [6,7,8,9,10], [11,12,13,14,15], [16,17,18,19,20], [21,22,23,24,25]]

    newmatrix=[] for y in range(0,5): for x in range(4,-1,-1): newmatrix.append(matrix[x][y])

    for i in range(0,25,5): print(newmatrix[i:i+5])

    reply permalink

  • Mark Murnane - 10 years, 9 months ago

    Two entries, depending what counts as cheating: [[x[n] for x in matrix[::-1]] for n in range(len(matrix))]

    import numpy as n n.rot90(n.array(matrix, int),3)

    reply permalink

  • El Ninja - 10 years, 9 months ago

    Got each function in just one line of code:

    # Matrix rotation CW
    def cw(m): 
        # transpose & reverse each row
        return zip(*m[::-1])
    
    # Matrix rotation CCW
    def ccw(m):
        # transpose & reverse each column
        return zip(*m)[::-1]
    

    much help to:

    http://stackoverflow.com/a/8664879/1599609

    another way to write the cw

    [e[::-1] for e in zip(*m)]

    reply permalink

  • Tavi - 10 years, 9 months ago

    js: var ret=[],n=5,i=0;for(i=0;i<n;i++){ret.push(mat.map(function(item){return item[n-i];}).reverse());} ret; cww: var ret=[],n=5,i=0;for(i=0;i<n;i++){ret.push(mat.map(function(item){return item[i];}));} ret.reverse();

    reply permalink

  • El Ninja - 10 years, 9 months ago

    There should be a way to edit comments, the python comments (with a hashbang) got translated to markdown as a title

    reply permalink

  • Mark Murnane - 10 years, 9 months ago

    Oops, accounting for the date:

    import numpy as n, datetime as d print(n.rot90(n.array(matrix, int), 3 if d.date.today().weekday()>4 else 1))

    reply permalink

  • Mei - 10 years, 9 months ago

    Not as concise as the Python example, but here's my JS attempt

    function rotate(matrix) { var today = new Date();

    var rotated = [];
    for(var i in matrix)
    {
        for(var j in matrix[i])
        {
            if(typeof(rotated[j]) == 'undefined') rotated[j] = [];
            if(today.getDay() >= 1|| today.getDay() < 6) // week
                rotated[j].unshift(matrix[i][j]);
            else
                rotated[j].shift(matrix[i][j]);
    
        }
    }
    return rotated;
    

    }

    reply permalink

  • JeanNiBee - 10 years, 9 months ago

    Having a hard time seeing how this works for counter clockwise... then again having a hard time fixing it 'elegantly'. :)

    When I run this and 'force' the counter clockwise rotation it's all blank arrays.

    reply permalink

  • Sebastian - 10 years, 9 months ago

    matrix' = let matrix = chunksOf 5 [1..25] in (fmap reverse . transpose) matrix

    reply permalink

  • furalyon - 10 years, 9 months ago

    python solution:

    given_matrix = [[1, 2, 3, 4, 5], [6, 7, 8, 9, 10], [11, 12, 13, 14, 15], [16, 17, 18, 19, 20], [21, 22, 23, 24, 25]]

    from datetime import date given_date = date.today()

    solution_matrix = [[given_matrix[4-j][i] if given_date.weekday()<5 else m[j][4-i] for j in range(5)] for i in range(5)]

    reply permalink

  • Keith Kei - 10 years, 9 months ago

    function rotate(m, direction) { if (!direction) direction = 'CW'; var rtn = [[],[],[],[],[]]; for (i = 0; i < m.length; i++) { for (j = 0; j < m[i].length; j++) {

                                            if (direction == 'CW')
                                                rtn[j].unshift(m[i][j]);
                                            else
                                                rtn[Math.abs(j - 4)].push(m[i][j]);
                                        }
                                    }
                                    return rtn;
                                }
                                console.log(rotate(matrix,'CCW'));
    

    reply permalink

  • Anonymous - 10 years, 9 months ago

    Scala: matrix.transpose.map(_.reverse)

    reply permalink

  • chamila - 10 years, 9 months ago

    Java

    import java.util.Calendar;

    public class RotateMatrix { public static void main (String[] args) { int[][] matrix = { {1,2,3,4,5}, {6,7,8,9,10}, {11,12,13,14,15}, {16,17,18,19,20}, {21,22,23,24,25} };

        display2dArray(matrix);
    
        int[][] rotated = rotate2dArray(matrix, 5);
    
        System.out.println("Rotated" + ((isWeekDay()) ? " clockwise" : " anticlockwise"));
        display2dArray(rotated);
    }
    
    private static int[][] rotate2dArray(int[][] matrix, int length)
    {
        int[][] rotated = new int[length][length];
        boolean clockwise = isWeekDay();
    
        for(int x=0; x < length; x++)
        {
            for(int y=0; y < length; y++)
            {
                if(clockwise)
                {
                    rotated[x][y] = matrix[length-1-y][x];
                }
                else 
                {
                    rotated[x][y] = matrix[y][length-1-x];
                }               
            }
        }
    
        return rotated;
    }
    
    private static boolean isWeekDay()
    {
        int today = Calendar.getInstance().get(Calendar.DAY_OF_WEEK);
        return (today != Calendar.SUNDAY && today != Calendar.SATURDAY) ? true : false;
    }
    
    private static void display2dArray(int[][] arr)
    {
        System.out.println("[");
        for(int x = 0; x < arr.length; x++)
        {
            System.out.print("[");
            for(int y = 0; y < arr.length; y++)
            {
                System.out.print(arr[x][y] + ",");
            }
    
            System.out.println("],");
        }
    
        System.out.println("]");
    }
    

    }

    reply permalink

  • Chris - 10 years, 9 months ago

    In Python you can rotate a matrix as such:

    zip(*matrix[::-1])
    

    CCW:

    zip(*matrix)[::-1]
    

    Here's a py3 class that implements it. Looks a bit worse because it returns list objects instead of iterators so I could read it :)

    class MatrixRotator(object):
        """
        Rotate a matrix.
        """
        def __init__(self, matrix):
            self.original = matrix
            self.matrix = matrix
    
        def reset(self):
            self.matrix = self.original
    
        def rotate_clockwise(self):
            self.matrix = list(map(list, zip(*self.matrix[::-1])))
    
        def rotate_counter_clockwise(self):
            self.matrix = list(map(list, list(zip(*self.matrix))[::-1]))
    
        def get_matrix(self):
            return self.matrix
    

    reply permalink

  • Luke Winship - 10 years, 9 months ago

    import datetime
    print [r[::-1]for r in zip(*matrix)]if datetime.date.today().weekday()<5 else zip(*matrix)[::-1]
    

    Matrix printed is a list of tuples rather than a list of lists but since you just want to get your dog out, I'm sure you wouldn't mind :P

    And yes I am going a little bit over the top with the whitespace but hey I want those bonus points

    reply permalink

  • nholland94 - 10 years, 9 months ago

    Here is a ruby implementation for a reverse method (already manually minified)

    def r(a,d=true)n=Array.new(a[0].length){[]};(d ? a.reverse : a).each{|r|(d ? r : r.reverse).each_with_index{|j,i|n[i].push(j)}};n;end

    So you could call it quite easily for whatever situation you would need. For instance, if you had an array (a) and wanted to decode based on the day like the example:

    require 'date' Date.today.cwday>5 ? r a,false : r a

    reply permalink

  • Anonymous - 10 years, 9 months ago

    Fortran!

    http://pastebin.com/4dq72Uhp

    reply permalink

  • Anonymous - 10 years, 9 months ago

    R solution:

    x <- matrix(c(1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25), 5, 5, byrow=T) sapply(nrow(x):1, function(i) x[i, ])

    reply permalink

  • Richard Hennigan - 10 years, 9 months ago

    import Data.List
    
    rotateCW ∷ [[a]] → [[a]]
    rotateCW m = map reverse (transpose m)
    
    rotateCCW ∷ [[a]] → [[a]]
    rotateCCW m = transpose $ map reverse m
    
    matrix ∷ [[Integer]]
    matrix = [[ 1, 2, 3, 4, 5],
              [ 6, 7, 8, 9,10],
              [11,12,13,14,15],
              [16,17,18,19,20],
              [21,22,23,24,25]]
    
    main ∷ IO ()
    main = do
        print $ rotateCCW matrix
    

    reply permalink

  • Richard Hennigan - 10 years, 9 months ago

    I can't reply to my previous comment due to the broken captcha, but I forgot to mention that my code is Haskell (in case you didn't know).

    Also, here's the Mathematica version for fun:

    Transpose[Reverse/@matrix]
    

    reply permalink

  • visgean - 10 years, 9 months ago

    https://gist.github.com/Visgean/9412877

    please fuck off with this captha thing. If you need to moderate comments against spam consider disqus.

    reply permalink

  • Scroph - 10 years, 9 months ago

    D solution for clockwise rotation of a matrix :

    import std.stdio;
    import std.conv;
    import std.string;
    import std.range;
    import std.functional : pipe;
    import std.algorithm : map;
    
    
    int main(string[] args)
    {
        int[][] matrix;
        int[][] reversed;
        string line;
    
        while((line = readln().strip()) != "")
        {
            matrix ~= line  .split(" ")
                    .map!(pipe!(to!string, to!int))
                    .array();
        }
    
        auto r = matrix.retro();
        foreach(k; 0 .. matrix.length)
        {
            reversed ~= r.transversal(k).array();
        }
    
        Printer!(int)(matrix);
        Printer!(int)(reversed);
    
        return 0;
    }
    
    void Printer(T)(T[][] matrix)
    {
        writeln("[");
        foreach(row; matrix)
        {
            write("\t[");
            foreach(cell; row)
            {
                write(cell);
                if(cell != row[$ - 1])
                    write(", ");
                else
                    writeln("]");
            }
        }
        writeln("]");
    }
    

    reply permalink

  • Manu Madhav - 10 years, 9 months ago

    % MATLAB if weekday(date)==1 | weekday(date)==7 fliplr(matrix)' else flipud(matrix)' end

    reply permalink

  • Daenks - 10 years, 9 months ago

    C# class to handle Encryption/Decryption

    class VCipher
    {
        private Dictionary<char, int> CharMap;
        public string message { get; set; }
        public string cipher { get; set; }
        public string result { get; set; }
    
        public VCipher()
        {
            message = "";
            cipher = "";
            result = "";
        }
        public VCipher(bool demo = false)
        {
            InitCharMap();
            if (demo)
            {
                Console.WriteLine("Decoding message KSGDGBJQBEQKKLGDG with key REDDIT");
                message = "KSGDGBJQBEQKKLGDG";
                cipher = "REDDIT";
                result = "";
                Console.WriteLine(DecodeMessage());
            }
        }
        public VCipher(string message, string cipher)
        {
            this.message = message;
            this.cipher = cipher;
            result = "";
        }
    
        void InitCharMap()
        {
            CharMap = new Dictionary<char, int>();
            CharMap.Add('A',0);
            CharMap.Add('B',1);
            CharMap.Add('C',2);
            CharMap.Add('D',3);
            CharMap.Add('E',4);
            CharMap.Add('F',5);
            CharMap.Add('G',6);
            CharMap.Add('H',7);
            CharMap.Add('I',8);
            CharMap.Add('J',9);
            CharMap.Add('K',10);
            CharMap.Add('L',11);
            CharMap.Add('M',12);
            CharMap.Add('N',13);
            CharMap.Add('O',14);
            CharMap.Add('P',15);
            CharMap.Add('Q',16);
            CharMap.Add('R',17);
            CharMap.Add('S',18);
            CharMap.Add('T',19);
            CharMap.Add('U',20);
            CharMap.Add('V',21);
            CharMap.Add('W',22);
            CharMap.Add('X',23);
            CharMap.Add('Y',24);
            CharMap.Add('Z',25);
        }
    
        private char EncodeCharacter(char Character, char cipherCharacter)
        {
            int OriginalValue = -1;
            int CipherValue = -1;
            int NewValue = -1;
    
            CharMap.TryGetValue(Character, out OriginalValue);
            CharMap.TryGetValue(cipherCharacter, out CipherValue);
            NewValue = (OriginalValue + CipherValue) % 26;
    
            return ReverseLookup(NewValue);
        }
        private char DecodeCharacter(char Character, char cipherCharacter)
        {
            int OriginalValue = -1;
            int CipherValue = -1;
            int NewValue = -1;
            CharMap.TryGetValue(Character, out OriginalValue);
            CharMap.TryGetValue(cipherCharacter, out CipherValue);
            NewValue = (OriginalValue - CipherValue) % 26;
            if (NewValue < 0)
                NewValue = 26 + NewValue;
    
            return ReverseLookup(NewValue);
        }
    
        public string EncodeMessage()
        {
            result = "";
            int c = 0;
            for (int m = 0; m < message.Length; m++)
            {
                if (c > (cipher.Length-1))
                    c = 0;
                result += EncodeCharacter(message[m], cipher[c]);
                c++;
            }
            return result;
        }
        public string EncodeMessage(string message, string cipher)
        {
            this.message = message;
            this.cipher = cipher;
            return EncodeMessage();
        }
    
        public string DecodeMessage()
        {
            result = "";
            int c = 0;
            for (int m = 0; m < message.Length; m++)
            {
                if (c > (cipher.Length - 1))
                    c = 0;
                result += DecodeCharacter(message[m], cipher[c]);
                c++;
            }
            return result;
        }
        public string DecodeMessage(string message, string cipher)
        {
            this.message = message;
            this.cipher = cipher;
            return DecodeMessage();
        }
    
        private char ReverseLookup(int num)
        {
            foreach (KeyValuePair<char, int> pair in CharMap)
            {
                if (pair.Value == num)
                    return pair.Key;
            }
            return '!';
        }
    }
    

    }

    reply permalink

  • Anonymous - 10 years, 9 months ago

    In place rotation in JavaScript:

    var rot90cw = function (arr) {
      for (var i = 0, len = arr.length, upb = len / 2; i < upb; i++) {
        for (var j = i; j < len - i - 1; j++) {
          //store top
          var top = arr[i][j];
          // move left to top
          arr[i][j] = arr[len - j - 1][i];
          // move bottom to left
          arr[len - j - 1][i] = arr[len - i - 1][len - j - 1];
          // move right to bottom
          arr[len - i - 1][len - j - 1] = arr[j][len - i - 1];
          // move top to right
          arr[j][len - i - 1] = top;
        }
      }
      return arr;
    };
    
    var decrypt = function (arr) {
      var today = (new Date()).getDay();
      if (today === 0 || today === 6) {
        // rot90cw 3* for ccw
        return rot90cw(rot90cw(rot90cw(arr)));
      }
      return rot90cw(arr);
    };
    

    reply permalink

  • Danois - 10 years, 9 months ago

    // JS

    // Impl. function move(d, inp, l, i) { if (i >= l*l) return inp; var x = d < 5 ? i % l : (l - 1) - i % l; var y = d < 5 ? (l - 1) - parseInt(i / l) : parseInt(i / l); var v = inp[parseInt(i / l)][i % l]; var m = move(d, inp, l, i + 1); m[x][y] = v; return m; }

    // Demo matrix=[[1,2,3,4,5,6], [7,8,9,10,11,12], [13,14,15,16,17,18], [19,20,21,22,23,24], [25,26,27,28,29,30], [31,32,33,34,35,36]];

    // move(zero based day of week, input matrix, N matrix size, 0) move(0, matrix, matrix.length, 0);

    // Output for monday: // 31 25 19 13 7 1 // 32 26 20 14 8 2 // 33 27 21 15 9 3 // 34 28 22 16 10 4 // 35 29 23 17 11 5 // 36 30 24 18 12 6

    reply permalink

  • Highsight - 10 years, 9 months ago

    Got a groovy implementation done in 500 characters. (including print matrix function)

    int[][] matrix=[[1,2,3,4,5], [6,7,8,9,10], [11,12,13,14,15], [16,17,18,19,20], [21,22,23,24,25]]

    printMatrix(rotateClockwise(matrix))

    def printMatrix(matrix) { for (line in matrix) println line println '' }

    def rotateClockwise(matrix) { def m = new int[matrix.length][matrix.length] for (x=0;x<matrix.length;x++) for (y=0;y<matrix.length;y++) m[x][matrix[0].length-1-y] = matrix[y][x] return m }

    reply permalink

  • Highsight - 10 years, 9 months ago

    Whoops! The formatting got screwed up, let me try again...

    <pre><code>int[][] matrix=[[1,2,3,4,5], [6,7,8,9,10], [11,12,13,14,15], [16,17,18,19,20], [21,22,23,24,25]]

    printMatrix(rotateClockwise(matrix))

    def printMatrix(matrix) { for (line in matrix) println line println '' }

    def rotateClockwise(matrix) { def m = new int[matrix.length][matrix.length] for (x=0;x<matrix.length;x++) for (y=0;y<matrix.length;y++) m[x][matrix[0].length-1-y] = matrix[y][x] return m }</code></pre>

    reply permalink

  • Highsight - 10 years, 9 months ago

    OK, taking the easy way out. Here's a pastebin: http://pastebin.com/hgy7PMkA

    Can anyone tell me how to do the formatting right? I can't seem to get it.

    reply permalink

  • Deele - 10 years, 9 months ago

    I posted my solution in http://snippetrepo.com/snippets/rotate-matrix

    reply permalink

  • Anonymous - 10 years, 9 months ago

    Scheme (define (rotate matrix day) (cond ((memq day '(saturday sunday)) (apply map list (map reverse matrix))) (else (map reverse (apply map list matrix)))))

    reply permalink

  • Jeff - 10 years, 9 months ago

    Simple implementation in Elm. Click on my name above to see the code in action.

    matrix=[ [ 1, 2, 3, 4, 5]
       , [ 6, 7, 8, 9,10]
       , [11,12,13,14,15]
       , [16,17,18,19,20]
       , [21,22,23,24,25]
       ]
    
    matrixColumns m = 
      let rows r c = zipWith (::) r c
          empty m  = map (always []) m
      in  foldr rows (empty m) m
    
    matrixRotateClockwise m = map reverse <| matrixColumns m
    
    matrixRotateCounterClockwise m = reverse <| matrixColumns m
    
    main = flow down <| map asText <| matrixRotateClockwise matrix
    

    reply permalink

  • Derek - 10 years, 9 months ago

    Ruby:

    require 'date'
    
    def rotate(matrix, date=Date.today)
      if [6,7].include?(date.wday)
        return matrix.transpose.reverse
      else
        return matrix.reverse.transpose
      end
    end
    

    reply permalink

  • Derek - 10 years, 9 months ago

    Argh! Sunday is 0:

    require 'date'
    
    def rotate(matrix, date=Date.today)
      if [0,6].include?(date.wday)
        return matrix.transpose.reverse
      else
        return matrix.reverse.transpose
      end
    end
    

    reply permalink

  • Danois - 10 years, 9 months ago

    A JS implementation at pastebin

    reply permalink

  • anton kropp - 10 years, 9 months ago

    lets do an f# version of rotation, could've been more concise but i broke it out for legibility.

    ` letrotate -90`` matrix = let rec rotateBackwards' matrix acc = match matrix with | (h::t)::_ -> // take the first element from each list let heads = List.map List.head matrix

            // get everything after the first element (so this is a new matrix of elements [[1..last]]
            let tails = List.map (Seq.skip 1 >> Seq.toList) matrix
    
            // pass in the matrix, and append all the first elements to the list (
            // this builds the list backwards, since we are appending to a cons cell list)       
            rotateBackwards' tails (heads::acc)
    
         | _ -> acc |> List.map Seq.toList
    
    rotateBackwards' matrix []
    

    ```

    reply permalink

  • Tom - 10 years, 9 months ago

    C:

    include <stdio.h>

    include <stdlib.h>

    define N 5

    int main(int argc, const char *argv[]) { int matrix[N][N] = { {1, 2, 3, 4, 5}, {6, 7, 8, 9, 10}, {11, 12, 13, 14, 15}, {16, 17, 18, 19, 20}, {21, 22, 23, 24, 25} }; int outmatrix[N][N]; int i, j; for(i = 0; i < N; i++) { for(j = N; j > 0; j--){ outmatrix[i][N - j] = matrix[j - 1][i]; } } return 0; }

    reply permalink

  • B - 10 years, 9 months ago

    Java Solution (quite long, but works. doesn't check for the day, but can call the rotate function to turn both ways)

    public class RotateMatrix {

    int[][] matrix = {{1,2,3,4,5},
            {6,7,8,9,10},
            {11,12,13,14,15},
            {16,17,18,19,20},
            {21,22,23,24,25}};
    int[][] newMatrix = new int[matrix.length][matrix[0].length];
    
    public static void main(String[] args) {
        RotateMatrix task = new RotateMatrix();
        task.rotate(-1);
        for(int i = 0; i < task.matrix.length; i++) {
            for(int j = 0; j < task.matrix[0].length; j++) {
                System.out.println(task.newMatrix[i][j]);
            }
        }
    }
    
    public void rotate(int direction) {
    
        if(direction == 1) {
            for (int i = 0; i < matrix.length; i++) {
                int cursor = 0;
                for(int j = matrix[0].length - 1; j >= 0; j--) {
                    newMatrix[i][cursor] = matrix[j][i];
                    cursor++;
                }
            }
        }
        else if(direction == -1) {
            int cursor = 0;
            for (int i = matrix.length - 1; i >= 0; i--) {
                for(int j = 0; j < matrix.length; j++) {
                    newMatrix[cursor][j] = matrix[j][i];
                }
                cursor++;
            }
        }
    }
    

    }

    reply permalink

  • Anonymous - 10 years, 9 months ago

    def rotate(m): n = len(m) target = copy.deepcopy(m) for i in xrange(n): for j in xrange(n): if date.today().isoweekday() <= 5: target[j][-i-1] = m[i][j] else: target[-j-1][i] = m[i][j] return target

    reply permalink

  • Anonymous - 10 years, 9 months ago

    In Javascript: <pre><code> var m=[[1,2,3,4,5], [6,7,8,9,10], [11,12,13,14,15], [16,17,18,19,20], [21,22,23,24,25]]

    function ccw(a) {return a[0].map(function(c, i) {return a.map(function(r) {return r[i]})})} function cw(a) {return ccw(a).map(function(c) {return c.reverse()})}

    console.log((new Date().getDay()==(0|6))?ccw(m).reverse():cw(m)) </code></pre>

    reply permalink

  • LHSP - 10 years, 9 months ago

    In Python:

    <pre> import datetime m = [[1,2,3,4,5],[6,7,8,9,10],[11,12,13,14,15],[16,17,18,19,20],[21,22,23,24,25]] if datetime.datetime.today().weekday() < 5: n = zip(m[::-1]) else : n = zip(m)[::-1] print n </pre>

    reply permalink

  • Inaccurate- - 10 years, 9 months ago

    From a purely mathematical perspective, this can be done using a simple formula.

    For every entry m[i][j] the equivalent entry in the rotated matrix m' is:

    x = (5*j)+i-4
    m'[x / 5][x % 5] = m[i][j]
    

    Generalized for any square matrix:

    l = length of one side 
    x = (l*j)+i-(l-1)
    m'[x / l][x % l] = m[i][j]
    

    reply permalink

  • Inaccurate- - 10 years, 9 months ago

    Or more simply (for cw):

    m'[j][4-i] = m[i][j]
    

    reply permalink

  • Verexa - 10 years, 9 months ago

    My solution in JavaScript... This is where I stored the matrix:

    m=[[1,2,3,4,5],
        [6,7,8,9,10],
        [11,12,13,14,15],
        [16,17,18,19,20],
        [21,22,23,24,25]];
    

    This is my code 178 characters:

    d=(new Date()).getDay();f=(function(v){n=[];s=v.length-1;x=s;y=s;while(x>=0){l=[];while(y>=0){l[y]=v[y][x];y--}n.push(l);x--;y=s}return n});if(d>5||d<1){k=f(m)}else{k=f(f(f(m)))}
    

    Print out the key:

    console.log(k);
    

    reply permalink

  • P M - 10 years, 9 months ago

    This is pretty trivial on Matlab

    reply permalink

  • jjj - 10 years, 9 months ago

    Definetly not the shortest or easiest but here is a c# implementation

    using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks;

    namespace ConsoleApplication2 { class Program { static void Main() {

            int[,] table = { { 1, 2, 3, 4, 5 }, { 6, 7, 8, 9, 10 }, { 11, 12, 13, 14, 15 }, { 16, 17, 18, 19, 20 }, { 21, 22, 23, 24, 25 } };
            for (int c = 0; c < 5; c++)
            {
                display(c, ref table);
            }
            Console.ReadLine();
            //Mondary-Friday 90 clockwise
            int[,] rotatedtable = rotateclk(table, 5);
            for (int c = 0; c < 5; c++)
            {
                display(c, ref rotatedtable);
            }
            Console.ReadLine();
            //Saturday and Sunday 90 degree counterclockwise
            int[,] rotatedtablecounter = rotatecntrclk(table, 5);
            for (int c = 0; c < 5; c++)
            {
                display(c, ref rotatedtablecounter);
            }
            Console.ReadLine();
        }
        static void display(int row, ref int[,] table)
        {
            bool oneshot = true;
    
                if (oneshot)
                {
                    Console.WriteLine();
                    oneshot = false;
                }
                for (int c = 0; c < 5; c++)
                {
    
                    Console.Write(table[row, c] + " ");
                }
    
            }
    
        static int[,] rotateclk(int[,] table, int size)
        {
            int[,] rotatedtable = new int[size,size];
            for (int col = 0; col < size; ++col)
            {
                for (int row = 0; row < size; ++row)
                {
                    rotatedtable[col, row] = table[size - row - 1, col];
                }
            }
            return rotatedtable;
        }
    
        static int[,] rotatecntrclk(int[,] table, int size)
        {
            int[,] rotatedtable = new int[size, size];
            for (int col = 0; col < size; ++col)
            {
                for (int row = 0; row < size; ++row)
                {
                    rotatedtable[col, row] = table[row, size - col - 1];
                }
            }
            return rotatedtable;
        }
    }
    }
    

    reply permalink

  • jjj - 10 years, 9 months ago

    Not the shortest, here is a c# implementation for any day

    using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks;

    namespace ConsoleApplication2 { class Program { static void Main() {

            int[,] table = { { 1, 2, 3, 4, 5 }, { 6, 7, 8, 9, 10 }, { 11, 12, 13, 14, 15 }, { 16, 17, 18, 19, 20 }, { 21, 22, 23, 24, 25 } };
            for (int c = 0; c < 5; c++)
            {
                display(c, ref table);
            }
            Console.ReadLine();
            //Mondary-Friday 90 clockwise
            int[,] rotatedtable = rotateclk(table, 5);
            for (int c = 0; c < 5; c++)
            {
                display(c, ref rotatedtable);
            }
            Console.ReadLine();
            //Saturday and Sunday 90 degree counterclockwise
            int[,] rotatedtablecounter = rotatecntrclk(table, 5);
            for (int c = 0; c < 5; c++)
            {
                display(c, ref rotatedtablecounter);
            }
            Console.ReadLine();
        }
        static void display(int row, ref int[,] table)
        {
            bool oneshot = true;
    
                if (oneshot)
                {
                    Console.WriteLine();
                    oneshot = false;
                }
                for (int c = 0; c < 5; c++)
                {
    
                    Console.Write(table[row, c] + " ");
                }
    
            }
    
        static int[,] rotateclk(int[,] table, int size)
        {
            int[,] rotatedtable = new int[size,size];
            for (int col = 0; col < size; ++col)
            {
                for (int row = 0; row < size; ++row)
                {
                    rotatedtable[col, row] = table[size - row - 1, col];
                }
            }
            return rotatedtable;
        }
    
        static int[,] rotatecntrclk(int[,] table, int size)
        {
            int[,] rotatedtable = new int[size, size];
            for (int col = 0; col < size; ++col)
            {
                for (int row = 0; row < size; ++row)
                {
                    rotatedtable[col, row] = table[row, size - col - 1];
                }
            }
            return rotatedtable;
        }
    }
    }
    

    reply permalink

  • gkprabhakar - 10 years, 9 months ago

    MATLAB code :

    fliplr(matrix')

    reply permalink

  • Londi - 10 years, 9 months ago

    C# : var m1 = new int[,] { { 1, 2, 3, 4, 5 }, { 6, 7, 8, 9, 10 }, { 11, 12, 13, 14, 15 }, { 16, 17, 18, 19, 20 }, { 21, 22, 23, 24, 25 } }; int l1 = m1.GetLength(0), l2 = m1.GetLength(1); var m2 = new int[l2, l1];

    for (var i = 0; i < l2; i++)
    {
        for (var j = 0; j < l1; j++)
        {
            m2[i, j] = (int)DateTime.Now.DayOfWeek > 5 ? m1[j, l1 - i - 1] : m1[l1 - j - 1, i];
            Console.Write(m2[i, j] + " ");
        }
    
        Console.WriteLine();
    }
    
    Console.ReadLine();
    

    reply permalink

  • Ryan Kelker - 10 years, 9 months ago

    Clojure solution:

    (defn rotate-right [coll] (let [mtx (reverse coll)] (apply mapv #(into [] %&) mtx)))

    Test Code

    ``` (defn rotate-right [coll] (let [mtx (reverse coll)] (apply mapv #(into [] %&) mtx)))

    (def m [[1 2 3 4 5] [6 7 8 9 10] [11 12 13 14 15] [16 17 18 19 20] [21 22 23 24 25]])

    (def solution [[21 16 11 6 1] [22 17 12 7 2] [23 18 13 8 3] [24 19 14 9 4] [25 20 15 10 5]])

    (def working? (= (rotate-right m) solution))

    reply permalink

  • Ryan Kelker - 10 years, 9 months ago

    A bettter formatted Clojure solution https://coderwall.com/p/-cpnbg

    reply permalink

  • mj - 10 years, 9 months ago

    def rotate_right(m): rows = len(m) cols = len(m[0]) r_matrix = [[0 for x in xrange(rows)] for x in xrange(cols)] for i in xrange(rows): for j in xrange(cols): r_matrix[i][j] = m[rows - j - 1][i] return r_matrix

    def rotate_left(m): return rotate_right(rotate_right(rotate_right(m)))

    reply permalink

  • Morganic - 10 years, 9 months ago

    Java solution which also lets you print the matrix. although it's a bit verbose and not very concise.

    <code> package seventhMarch;

    public class MatrixRotator {

    private String matrix;
    private String[][] matrixRepresentation;
    private int matrixHeight;
    private int matrixLength;
    
    
    public static void main(String[] args) {
    
        String matrix =
                "[[1,2,3,4,5],\n" +
                        "[6,7,8,9,10],\n" +
                        "[11,12,13,14,15],\n" +
                        "[16,17,18,19,20],\n" +
                        "[21,22,23,24,25]]";
    
        MatrixRotator matrixRotator = new MatrixRotator(matrix);
        matrixRotator.rotateClockwise();
        System.out.println(matrixRotator);
        System.out.println("------------");
        matrixRotator.rotateCounterClockwise();
        System.out.println(matrixRotator);
        System.out.println("------------");
        matrixRotator.rotateCounterClockwise();
        System.out.println(matrixRotator);
    }
    
    public MatrixRotator(String matrix){
        this.matrix = matrix;
        String[] lines = matrix.split("\n");
        matrixHeight = lines.length;
        matrixLength = lines[0].split(",").length;
        matrixRepresentation = new String[matrixHeight][matrixLength];
    
        // Setups initial Matrix Representation in a 2-way array.
        for(int i = 0; i  < matrixHeight; i++){
            for(int j = 0; j < matrixLength; j++){
                matrixRepresentation[i][j] = lines[i].split(",")[j].replace("[","").replace("]","");
            }
        }
    }
    
    public void rotateClockwise(){
        String[][] tempRepresentation = new String[matrixHeight][matrixLength];
    
        for(int i = 0; i < matrixHeight; i++){
            for(int j = 0; j < matrixLength; j++)
                tempRepresentation[i][j] = matrixRepresentation[matrixHeight - 1 - j][i];
        }
        matrixRepresentation = tempRepresentation;
    }
    
    public void rotateCounterClockwise(){
        String[][] tempRepresentation = new String[matrixHeight][matrixLength];
    
        for(int i = 0; i < matrixHeight; i++){
            for(int j = 0; j < matrixLength; j++)
                tempRepresentation[j][i] = matrixRepresentation[i][matrixLength - 1 - j];
        }
        matrixRepresentation = tempRepresentation;
    }
    
    
    public String toString(){
        String result = "[[";
    
        for(int i = 0; i < matrixHeight; i++){
            for(int j = 0; j < matrixLength; j++){
                if(j != matrixLength-1) result = result + matrixRepresentation[i][j] + ",";
                else result = result + matrixRepresentation[i][j];
            }
            if(i != matrixHeight-1) result = result + "],\n[";
            else result = result + "]]";
        }
    
        return result;
    }
    

    }

    </code>

    reply permalink

  • Anonymous - 10 years, 9 months ago

    Ruby script (108 char). Just pass in any matrix and watch it go! require 'date';print Date.today.cwday>5 ? eval(ARGV[0]).transpose.reverse : eval(ARGV[0]).reverse.transpose

    reply permalink

  • JeanNiBee - 10 years, 9 months ago

    My shot at in in Javascript. Little more verbose, purposely so people can read it if needed.

    var Sarantakos = (function () {
        return {
            rotate: function (m, dir) {
                var flipped = [];
                m.forEach(function (val, idx, arr) {
                    val.forEach(function (jal, jdx, jarr) {
                        if (dir) {
                            if (typeof(flipped[jdx]) == 'undefined') flipped[jdx] = [];
                            flipped[jdx].unshift(arr[idx][jdx]);
                        } else {
                            if (typeof(flipped[(jarr.length-1)-jdx]) == 'undefined') flipped[(jarr.length-1)-jdx] = [];
                            flipped[(jarr.length-1)-jdx].push(arr[idx][jdx]);
                        }
                    });
                });
                return flipped;
            }
        };
    })();
    
    var now = new Date().getDay();
    var clockwise = ((now >= 1 || now < 6)) ? true : false;
    var matrix = [[1,2,3,4,5],[6,7,8,9,10],[11,12,13,14,15],[16,17,18,19,20],[21,22,23,24,25]];
    console.log('Original Matrix:');
    console.dir(matrix);
    console.log('Rotated using day of week:');
    console.dir(Sarantakos.rotate(matrix, clockwise));
    console.log('(test) Rotated clockwise:');
    console.dir(Sarantakos.rotate(matrix, true));
    console.log('(test) Rotated counter-clockwise:')
    console.dir(Sarantakos.rotate(matrix, false));
    

    reply permalink

  • JeanNiBee - 10 years, 9 months ago

    Simplified again. (new val.forEach block)

    val.forEach(function (jal, jdx, jarr) {
        if (typeof(flipped[jdx]) == 'undefined') flipped[jdx] = [];
        if (dir) {
            flipped[jdx].unshift(arr[idx][jdx]);
        } else {
            flipped[jdx].push(arr[idx][(jarr.length-1)-jdx]);
        }
    });
    

    reply permalink

  • Hueho - 10 years, 9 months ago

    Running code here: http://repl.it/Pf3/1

    For anybody not wanting to click the link, here is my attempt in Javascript, and fuck verbosity: ` function transpose(anMatrix) { var result = []; var size = anMatrix.length; for(var i = 0; i < size; i++) { var line = []; for(var j = 0; j < size; j++) { line.push(anMatrix[j][i]); } result.push(line); } return result; }

    function reverseOf(anArray) { var result = []; for(var i = anArray.length - 1; i >= 0; i--) { result.push(anArray[i]); } return result; }

    function rotateClock(anMatrix) { return transpose(anMatrix).map(reverseOf); }

    function rotateCounter(anMatrix) { return transpose(anMatrix.map(reverseOf)); } `

    The important part is really the transpose function, from there you just have to reverse the lines either before or after transposing the matrix, depending what rotation do you want.

    reply permalink

  • Ian Ker-Seymer - 10 years, 9 months ago

    Got suckered into doing this :)

    I didn't bother with the timing, just flipped it back to normal. Found a neat way to do it mathematically without any libs or external methods. Could minimize lines, but wanted to keep it legible.

    <code> matrix = [[21, 16, 11, 6, 1], [22, 17, 12, 7, 2], [23, 18, 13, 8, 3], [24, 19, 14, 9, 4], [25, 20, 15, 10,5]]

    def rowFlipper( bias, row ): for i in range( len(row) ): row[i] -= bias bias -= 6 return row

    def matrixFlipper( matrix ): unlocked =[] for i in range ( len(matrix) ): unlocked.append( rowFlipper( 20 - 4*i, matrix[i] )) return unlocked

    print matrixFlipper( matrix ) </code>

    reply permalink

  • Anonymous - 10 years, 9 months ago

    I didn't bother with the timing, just flipped it back to normal. Found a neat way to do it mathematically without any libs or external methods.

    def rowFlipper( bias, row ):
            for i in range( len(row) ):
                    row[i] -= bias
                    bias   -= 6
            return row
    
    def matrixFlipper( matrix ):
            unlocked =[]
            for i in range ( len(matrix) ):
                 unlocked.append( rowFlipper( 20 - 4*i, matrix[i] ))
            return unlocked
    
    print matrixFlipper( matrix )
    

    reply permalink

  • celacanto - 10 years, 9 months ago

    R m <- matrix(1:25, ncol = 5, byrow = TRUE) if(as.POSIXlt(Sys.Date())$wday < 6) apply(m, 1, rev) else t(apply(t(m), 1, rev))

    reply permalink

  • celacanto - 10 years, 9 months ago

    R

                m = matrix(1:25, ncol = 5, byrow = TRUE)
    
                 if(as.POSIXlt(Sys.Date())$wday < 6) apply(m, 1, rev) else t(apply(t(m), 1, rev))
    

    reply permalink

  • celacanto - 10 years, 9 months ago

    fix weekdays condition:

    R

    m = matrix(1:25, ncol = 5, byrow = TRUE)
    if(as.POSIXlt(Sys.Date())$wday < 6) t(apply(t(m), 1, rev)) else apply(m, 1, rev)
    

    reply permalink

  • Shay - 10 years, 9 months ago

    def martrix_rotate(m, d): n=len(m) c=[[None]*n for i in range(n)] for i,r in enumerate(reversed(m)): for j,e in enumerate(r): (x,y) = (n-1-j,n-1-i) if d in [1,7] else (j,i) c[x][y] = e return c

    reply permalink

  • robacarp - 10 years, 9 months ago

    In ruby, manually:

    def rot dir, matrix
      n = matrix[0].length
      left = dir == :left
      new = []
      n.times { new.push([]) }
      new.each{ |row| n.times { row.push([]) } }
    
      n -= 1
      (0..n).each do |i|
        (0..n).each do |j|
          new[i][j] = left ? matrix[j][n-i] : matrix[n-j][i]
        end
      end
    
      new
    end
    
    def get_key input
      dir = Time.new.wday >= 6
      rot dir ? :left : :right, input
    end
    

    reply permalink

  • Jabbersii - 10 years, 9 months ago

    Got it in Haskell:

    import Data.List
    rotClockwise = map reverse (transpose matrix)
    rotCounterClockwise = transpose (map reverse matrix)
    

    reply permalink

  • Samuel Chase - 10 years, 9 months ago

    ```lisp

    (defvar unrotated-array (make-array '(5 5) :initial-contents '((1 2 3 4 5) (6 7 8 9 10) (11 12 13 14 15) (16 17 18 19 20) (21 22 23 24 25))))

    (defun decide-rotation-direction (day) (if (find day '(mon tue wed thu fri)) 'right 'left))

    (defun rotate-matrix (matrix direction) (let* ((dimensions (array-dimensions matrix)) (rows (first dimensions)) (cols (second dimensions)) (rotated-matrix (make-array dimensions))) (dotimes (i rows) (dotimes (j cols) (if (eq direction 'right) (setf (aref rotated-matrix j (- (1- rows) i)) (aref matrix i j)) (setf (aref rotated-matrix (- (1- rows) j) i) (aref matrix i j))))) rotated-matrix))

    (defun open-lock (unrotated-key day) (rotate-matrix unrotated-key (decide-rotation-direction day)))

    (defun print-matrix (matrix) (let* ((dimensions (array-dimensions matrix)) (rows (first dimensions)) (cols (second dimensions))) (loop for i upto (1- rows) do (loop for j upto (1- cols) do (format t "~2a " (aref matrix i j)) finally (terpri)))))

    ```

    reply permalink

  • mike - 10 years, 9 months ago

    one liner in r:

    matrix.rotate <- function(matrix) t(apply(matrix,1,rev))

    reply permalink

Content curated by @MaxBurstein