본문 바로가기

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

[PS/Clojure] HackerRand - Algorithms - Absolute Permutation

아.. 뭔가 더 짤수있을꺼같은데..

Stream 규칙을 어떻게 세워야 할지 모르겠다.

 

필자가 적용한 알고리즘의 기초는

k가 2인경우 : 2 2 -2 -2 2 2 -2 -2 ....

k가 3인경우 : 3 3 3 -3 -3 -3 3 3 3 -3 -3 -3 ..

이렇게 스트림에 더한것이 정상적인지 확인.

 

www.hackerrank.com/challenges/absolute-permutation/problem

 

Absolute Permutation | HackerRank

Find lexicographically smallest absolute permutation.

www.hackerrank.com

github.com/Lee-WonJun/ProblemSolving/blob/master/Brute%20Force/Absolute%20Permutation/wjlee.clj

 

Lee-WonJun/ProblemSolving

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

github.com

 

(defn int-div [v] (int (/ v 2)))

(defn make-avail-helper [r n k]
  (let [repeat-k (repeat k k)
        repeat-k-minus (repeat k (- k))
        repeat-k-and-k-minus (concat repeat-k repeat-k-minus)
        mapped (take n (flatten (repeat (inc (/ n (* 2 k))) repeat-k-and-k-minus)))]
    (map + r mapped)))

(defn make-avail [n k]
  (let [r (range 1 (inc n))]
    (if (zero? k) r (make-avail-helper r n k))))

(defn absolutePermutation [n k]
  (let [avail-s (make-avail n k)
        sort-avail (sort avail-s)]
    (if (= sort-avail (range 1 (inc n)))  avail-s [-1])))
728x90