Problem
Determine whether an array is "Rainbow", i.e. it has the following structure:
- First a1 elements equal 1.
- Next a2 elements equal 2.
- Next a3 elements equal 3.
- Next a4 elements equal 4.
- Next a5 elements equal 5.
- Next a6 elements equal 6.
- Next a7 elements equal 7.
- Next a6 elements equal 6.
- Next a5 elements equal 5.
- Next a4 elements equal 4.
- Next a3 elements equal 3.
- Next a2 elements equal 2.
- Next a1 elements equal 1.
ai can be any positive integer. There are no other elements in array.
Solution
(defn palindrome? [items]
"Efficient algorithm: loops through only (array-size/2)"
(loop [i 0
j (-> items count dec)]
(cond (>= i j)
true
(not= (nth items i)
(nth items j))
false
:else
(recur (inc i) (dec j)))))
(let [test-cases-count (Integer/parseInt (read-line))
test-cases (for [i (range test-cases-count)]
(let [nums-count (read-line)
nums-temp (-> (read-line) (clojure.string/split #"\s+"))
nums (map #(Integer/parseInt %) nums-temp)]
nums))]
(for [t test-cases]
(if (palindrome? t)
(println "Yes")
(println "No"))))
Not able to figure out how to optimize this.