본문 바로가기

프로그래밍 기술 노트/Problem Solving

[PS/Clojure] HackerRand - Algorithms - Forming a Magic Square

Implementation 항목의 Magic Square, BruteForce 로 풀었다.

처음에는 time out나서 BruteForce 가 아닌가 했는데.. filter 를 안걸어주었었다.

모든 순열을 구하는데 사용한 permutations 코드는 그냥 인터넷에서 긁어왔다 ;;

C++ 은 next_permutation이 STL 에 있는데 clojure에 있는 clojure.math.combinatorics 가 HackerRank에서 지원을 안해준다 크흠..

 

 

Forming a Magic Square | HackerRank

Find the minimum cost of converting a 3 by 3 matrix into a magic square.

www.hackerrank.com

 

 

Lee-WonJun/ProblemSolving

알고리즘 세미나 . Contribute to Lee-WonJun/ProblemSolving development by creating an account on GitHub.

github.com

 

(defn permutations [s]
  (lazy-seq
   (if (next s)
     (for [head s
           tail (permutations (disj s head))]
          (cons head tail))
          [s])))

(defn is-magic [s]
    (let [[v1 v2 v3 v4 v5 v6 v7 v8 v9] s]
        (= (+ v1 v2 v3) 
           (+ v4 v5 v6) 
           (+ v7 v8 v9)
           (+ v1 v4 v7)
           (+ v2 v5 v8)
           (+ v3 v6 v9)
           (+ v1 v5 v9)
           (+ v3 v5 v7))))

(defn abs [x] (max x (- x)))

(defn calc-list [f s]
    (reduce + (map abs (map - f s))))

; Complete the formingMagicSquare function below.
(defn formingMagicSquare [s]
    (let [f (flatten s)
          magic (filter is-magic (permutations #{1 2 3 4 5 6 7 8 9}))]
          (apply min (map #(calc-list f %) magic))))

 

 

728x90