Implementation 항목의 Magic Square, BruteForce 로 풀었다.
처음에는 time out나서 BruteForce 가 아닌가 했는데.. filter 를 안걸어주었었다.
모든 순열을 구하는데 사용한 permutations 코드는 그냥 인터넷에서 긁어왔다 ;;
C++ 은 next_permutation이 STL 에 있는데 clojure에 있는 clojure.math.combinatorics 가 HackerRank에서 지원을 안해준다 크흠..
(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
'프로그래밍 기술 노트 > Problem Solving' 카테고리의 다른 글
[PS/C#] HackerRand - Algorithms - The Maximum Subarray (0) | 2020.11.03 |
---|---|
[PS/Clojure] HackerRand - Algorithms - Queen's Attack (0) | 2020.06.10 |
[PS/Clojure] HackerRand - Algorithms - Absolute Permutation (0) | 2020.06.08 |
[PS/Clojure] HackerRand - Algorithms - Sherlock and Cost (0) | 2020.06.05 |
[PS/Clojure] HackerRand - Algorithms - Equal (0) | 2020.06.05 |