From 34e55ef696e3d4657f5d788bd3f0e3aa4ac0e554 Mon Sep 17 00:00:00 2001 From: Scientific Coder Date: Thu, 18 Aug 2011 15:23:47 +0200 Subject: [PATCH 1/2] remove a count --- list-reduction/josephus.clj | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/list-reduction/josephus.clj b/list-reduction/josephus.clj index 3f52ada..3873ac8 100644 --- a/list-reduction/josephus.clj +++ b/list-reduction/josephus.clj @@ -1,5 +1,5 @@ (defn shout [counter nth coll] - (if (== (count coll) 1) + (if (empty? (rest coll)) (first coll) (shout (rem (+ counter (count coll)) nth) From 81c310423e58be2594cb4c2806621751a4c15f6e Mon Sep 17 00:00:00 2001 From: Scientific Coder Date: Thu, 18 Aug 2011 15:26:38 +0200 Subject: [PATCH 2/2] custom recursive Clojure code --- list-reduction/josephus.clj | 24 +++++++++++++++++------- 1 file changed, 17 insertions(+), 7 deletions(-) diff --git a/list-reduction/josephus.clj b/list-reduction/josephus.clj index 3873ac8..f24aa5f 100644 --- a/list-reduction/josephus.clj +++ b/list-reduction/josephus.clj @@ -1,13 +1,23 @@ -(defn shout [counter nth coll] - (if (empty? (rest coll)) +(defn shout + ([nth coll] (let [to-kill (dec nth)] (shout to-kill to-kill coll))) + ([counter to-kill coll] + (if (empty? (rest coll)) (first coll) - (shout - (rem (+ counter (count coll)) nth) - nth - (keep-indexed #(if(not= 0 (rem (+ %1 counter) nth)) %2) coll)))) + (let [[next-counter next-coll] + (loop [current-idx counter + to-process coll + res []] + (if (empty? to-process) + [current-idx res] + (if (== current-idx to-kill) + (recur 0 (rest to-process) res) + (recur (unchecked-inc current-idx) + (rest to-process) + (conj res (first to-process))))))] + (recur next-counter to-kill next-coll))))) (defn josephus [people nth] - (shout 0 nth (range 1 (inc people)))) + (shout nth (range 1 (inc people)))) ;(defn countdown [iterations] ; (dotimes [_ iterations]