diff --git a/.gitignore b/.gitignore index ee508f7..98a2a4b 100644 --- a/.gitignore +++ b/.gitignore @@ -8,3 +8,5 @@ pom.xml .lein-deps-sum .lein-failures .lein-plugins +/.idea +.lein-repl-history diff --git a/.nrepl-port b/.nrepl-port new file mode 100644 index 0000000..c48cdde --- /dev/null +++ b/.nrepl-port @@ -0,0 +1 @@ +42923 \ No newline at end of file diff --git a/looping-is-recursion-1.iml b/looping-is-recursion-1.iml new file mode 100644 index 0000000..9ac976c --- /dev/null +++ b/looping-is-recursion-1.iml @@ -0,0 +1,69 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/looping-is-recursion.iml b/looping-is-recursion.iml new file mode 100644 index 0000000..d5ac004 --- /dev/null +++ b/looping-is-recursion.iml @@ -0,0 +1,11 @@ + + + + + + + + + + + \ No newline at end of file diff --git a/src/looping_is_recursion.clj b/src/looping_is_recursion.clj index 199a5ce..023297d 100644 --- a/src/looping_is_recursion.clj +++ b/src/looping_is_recursion.clj @@ -1,26 +1,91 @@ (ns looping-is-recursion) (defn power [base exp] - ":(") + (cond + (zero? base) + 0 + (= exp 0) + 1 + :else + (let [helper (fn [acc n] + (if (= n 1) + acc + (recur (* acc base) (dec n))))] + (helper base exp)))) (defn last-element [a-seq] - ":(") + (let [helper (fn [acc the-seq] + (if (empty? the-seq) + acc + (recur (first the-seq) (rest the-seq))))] + (helper (first a-seq) (rest a-seq)))) (defn seq= [seq1 seq2] - ":(") + (let [helper (fn [acc new-seq1 new-seq2] + (cond + (and (empty? new-seq1) (empty? new-seq2)) + acc + (or (empty? new-seq1) (empty? new-seq2)) + false + :else + (recur (= (first new-seq1) (first new-seq2)) (rest new-seq1) (rest new-seq2))))] + (helper true seq1 seq2))) (defn find-first-index [pred a-seq] - ":(") + (loop [index 0 + the-pred pred + the-seq a-seq + ] + (cond + (empty? the-seq) + nil + (the-pred (first the-seq)) + index + :else + (recur (inc index) the-pred (rest the-seq))))) (defn avg [a-seq] - -1) + (loop [the-sum 0 + the-count 0 + the-seq a-seq + ] + (if (empty? the-seq) + (if (zero? the-count) + nil + (/ the-sum the-count)) + (recur (+ the-sum (first the-seq)) (inc the-count) (rest the-seq))))) + +(defn toggle [a-set elem] + (if (contains? a-set elem) + (disj a-set elem) + (conj a-set elem))) (defn parity [a-seq] - ":(") + (loop [result-set #{} + rest-of-set a-seq] + (if (empty? rest-of-set) + result-set + (recur (toggle result-set (first rest-of-set)) + (rest rest-of-set))))) (defn fast-fibo [n] - ":(") + (if (< n 2) + n + (loop [index 2 + f-n-1 1 + f-n 1] + (if (= index n) + f-n + (recur (inc index) f-n (+ f-n-1 f-n)))))) (defn cut-at-repetition [a-seq] - [":("]) + (loop [result-seq [] + remaining-seq a-seq] + (cond + (empty? remaining-seq) + result-seq + (true? (some #(= (first remaining-seq) %) result-seq)) + result-seq + :else + (recur (conj result-seq (first remaining-seq)) (rest remaining-seq)))))