m1epoq
Last Updated: February 25, 2016
·
1.056K
· runexec

A Clojure solution for a matrix rotation problem on problemotd.com

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?

(import 'java.util.Calendar)

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

(defn rotate-left [coll]
  (-> coll reverse rotate-right reverse))

(defn rotatation-by-day [coll]
  (let [today (-> (Calendar/getInstance)
                  (.get Calendar/DAY_OF_WEEK))
        weekend? (or (= today Calendar/SATURDAY)
                     (= today Calendar/SUNDAY))]
    (if-not weekend?
      (rotate-right coll)
      (rotate-left coll))))        

Solution test

(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-right [[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 solution-left [[5 10 15 20 25]
                    [4 9 14 19 24]
                    [3 8 13 18 23]
                    [2 7 12 17 22]
                    [1 6 11 16 21]])

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