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.
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:
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();
}
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++) {
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} };
}
reply permalink
Chris - 10 years, 9 months ago
In Python you can rotate a matrix as such:
CCW:
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 :)
reply permalink
Luke Winship - 10 years, 9 months ago
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
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:
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 :
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
}
reply permalink
Anonymous - 10 years, 9 months ago
In place rotation in JavaScript:
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.
reply permalink
Derek - 10 years, 9 months ago
Ruby:
reply permalink
Derek - 10 years, 9 months ago
Argh! Sunday is 0:
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.
` let
rotate -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```
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 {
}
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:
Generalized for any square matrix:
reply permalink
Inaccurate- - 10 years, 9 months ago
Or more simply (for cw):
reply permalink
Verexa - 10 years, 9 months ago
My solution in JavaScript... This is where I stored the matrix:
This is my code 178 characters:
Print out the key:
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() {
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() {
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];
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 {
}
</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.
reply permalink
JeanNiBee - 10 years, 9 months ago
Simplified again. (new val.forEach block)
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.
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
reply permalink
celacanto - 10 years, 9 months ago
fix weekdays condition:
R
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:
reply permalink
Jabbersii - 10 years, 9 months ago
Got it in Haskell:
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