99 Clojure Problems (19-22)

First off, thanks to all the commenters that have been contributing advice and corrections! It’s definitely helping, and I think I’m making some good progress on my quest.

Here’s another set of simple problems:

; P19 (**) Rotate a list N places to the left.
(defn rotate [n input]
  (let [amount (if (< n 0) (+ n (count input)) n)]
    (concat (drop amount input) (slice 0 amount input))))

; P20 (*) Remove the K'th element from a list.
(defn remove_at [k input]
  (list
    (concat
      (slice 0 k input)
      (slice (inc k) (count input) input))
    (nth input k)))

; P21 (*) Insert an element at a given position into a list.
(defn insert_at [k value input]
  (concat
    (slice 0  k input)
    (list value)
    (slice k (count input) input)))

; P22 (*) Create a list containing all integers within a given range.
(comment "clojure already has a (range a b), but it is [a,b), not [a,b]")
(defn s99_range [s e]
  (loop [output (list s)
         curr (inc s)]
    (if (> curr e)
      (reverse output)
      (recur (cons curr output) (inc curr)))))

Taking some comments to heart, I came up with an alternate P22. I’m not sure, though whether it’s better or worse than my original. I’m pretty sure that there’s a pretty big difference between the two, but I don’t know enough to say what’s what.

; P22 (*) Create a list containing all integers within a given range.
; clojure already has a (range a b), but it is [a,b), not [a,b]
(defn s99_range_v [s e] 
  (loop [output [s] 
         curr (inc s)] 
    (if (> curr e) 
      output 
      (recur (conj output curr) (inc curr)))))

The next block may take a while. I’m encountering some real difficulty with P26, but I don’t think I’m ready to start “cheating” and looking for other people’s solutions yet.

Leave a Reply

Your email address will not be published. Required fields are marked *

jon.com.org.net is using WP-Gravatar