Skip to content

Instantly share code, notes, and snippets.

@zaneli
Last active August 29, 2015 14:00
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save zaneli/11090532 to your computer and use it in GitHub Desktop.
Save zaneli/11090532 to your computer and use it in GitHub Desktop.
「ClojureでNinety-Nine Lisp Problems(P21~25)」ブログ用
(defn my-insert-at
"Insert an element at a given position into a list."
[x xs n]
(reverse (first (reduce (fn [[elems cnt] elem]
[(if (not= cnt n) (cons elem elems) (cons elem (cons x elems))), (inc cnt)]
) [nil, 1] xs)))
)
(defn my-insert-at
"Insert an element at a given position into a list."
[x xs n]
(let [[f s] (split-at (dec n) xs)] (concat f (cons x s)))
)
(defn my-range
"Create a list containing all integers within a given range."
[n m]
(reverse (
#(if (> %1 %2)
%3
(recur (inc %1) %2 (cons %1 %3)))
n m nil)
)
)
(defn my-remove-at
"Remove the K'th element from a list."
[xs n]
(let [[f s] (split-at (dec n) xs)] (concat f (rest s)))
)
(defn my-rnd-select
"Extract a given number of randomly selected elements from a list."
[xs n]
(#(if (>= (count %2) n)
%2
(let [n (rand-int (count %1))]
(recur (my-remove-at %1 n) (cons (nth %1 n) %2))
)
) xs nil)
)
(defn my-rnd-select
"Extract a given number of randomly selected elements from a list."
[xs n]
(defn my-remove-at
[xs n]
(let [[f s] (split-at n xs), [elem & rst] s] [elem (concat f rst)])
)
(#(if (>= (count %2) n)
%2
(let [n (rand-int (count %1)), [elem lst] (my-remove-at %1 n)]
(recur lst (cons elem %2))
)
) xs nil)
)
(defn my-rnd-select
"Extract a given number of randomly selected elements from a list."
[xs n]
(#(if (>= (count %2) n)
%2
(let [[fst & rst] (shuffle %1)]
(recur rst (cons fst %2))
)
) xs nil)
)
(defn my-rnd-select
"Extract a given number of randomly selected elements from a list."
[xs n]
(#(if (>= (count %2) n)
%2
(let [[fst & rst] (shuffle %1)]
(recur rst (cons fst %2))
)
) xs nil)
)
(defn my-lotto-select
"Lotto: Draw N different random numbers from the set 1..M."
[n m]
(my-rnd-select (range 1 (inc m)) n)
)
(defn my-lotto-select
"Lotto: Draw N different random numbers from the set 1..M."
[n m]
(let [n (min n m)]
(list*
(#(if (>= (count %) n)
%
(recur (conj % (inc (rand-int m))))
) #{}
)
)
)
)
(defn my-rnd-permu
"Generate a random permutation of the elements of a list."
[xs]
(reduce
#(if (== 0 (rand-int 2))
(cons %2 %1)
(concat %1 (list %2))
) nil xs)
)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment