Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

done'd #613

Open
wants to merge 2 commits into
base: master
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
68 changes: 60 additions & 8 deletions src/looping_is_recursion.clj
Original file line number Diff line number Diff line change
@@ -1,26 +1,78 @@
(ns looping-is-recursion)

(defn power [base exp]
":(")
(let [iter (fn [base exp acc] (if (zero? exp)
acc
(recur base (dec exp) (* base acc))))]
(iter base exp 1)))

(defn last-element [a-seq]
":(")
(let [iter (fn [b-seq elem] (if (empty? b-seq)
elem
(recur (rest b-seq) (first b-seq))))]
(iter a-seq nil)))

(defn seq= [seq1 seq2]
":(")
(let [iter (fn [xs ys] (cond
(and (empty? xs) (empty? ys)) true
(not (= (first xs) (first ys))) false
:else (recur (rest xs) (rest ys))))]
(if (== (count seq1) (count seq2))
(iter seq1 seq2)
false)))

(defn find-first-index [pred a-seq]
":(")
(loop [xs a-seq
elem (first a-seq)
index 0]
(cond
(empty? xs) nil
(pred elem) index
:else (recur (rest xs)
(first (rest xs))
(inc index)))))

(defn avg [a-seq]
-1)
(let [iter (fn [sum cnt xs] (if (empty? xs)
(/ sum cnt)
(recur (+ sum (first xs))
(inc cnt)
(rest xs))))]
(if (empty? a-seq)
nil
(iter 0 0 a-seq))))

(defn toggle [a-set elem]
(if (contains? a-set elem)
(disj a-set elem)
(conj a-set elem)))

(defn parity [a-seq]
":(")
(loop [a-set #{}
xs a-seq]
(if (empty? xs)
a-set
(recur (toggle a-set (first xs))
(rest xs)))))

(defn fast-fibo [n]
":(")
(loop [cur 1
prev 0
c 0]
(if (= c n)
prev
(recur (+ cur prev)
cur
(inc c)))))

(defn cut-at-repetition [a-seq]
[":("])
(loop [a-set #{}
init []
xs a-seq]
(cond
(empty? xs) init
(contains? a-set (first xs)) init
:else (recur (conj a-set (first xs))
(conj init (first xs))
(rest xs)))))