Last active
August 29, 2015 14:15
-
-
Save zaneli/02291b912faa9a6e17b5 to your computer and use it in GitHub Desktop.
「ClojureでNinety-Nine Lisp Problems(P26~28)」ブログ用
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
(defn my-combination | |
"Generate the combinations of K distinct objects chosen from the N elements of a list." | |
([n xs] (my-combination n xs nil)) | |
([n xs ys] | |
(if (== n 0) | |
(list (reverse ys)) | |
(mapcat | |
#(let [[z & zs] (drop % xs)] (my-combination (dec n) zs (cons z ys))) | |
(range 0 (- (count xs) (dec n))) | |
) | |
) | |
) | |
) |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
(declare my-combination not-contain?) | |
(defn my-group3 | |
"Group the elements of a set into disjoint subsets. (subgroups of 2, 3 and 4)" | |
[xs] | |
(let [xss (my-combination 2 xs)] | |
(mapcat | |
(fn [ys] | |
(let [ys' (filter #(not-contain? % ys) xs), yss (my-combination 3 ys')] | |
(map (fn [zs] | |
(list ys zs (filter #(not-contain? % zs) ys')) | |
) yss) | |
) | |
) xss) | |
) | |
) | |
(defn my-group | |
"Group the elements of a set into disjoint subsets. (subgroups of variable numbers)" | |
([xs ns] (my-group xs ns nil)) | |
([xs ns ys] | |
(if (nil? ns) | |
(list (reverse ys)) | |
(let [[m & ms] ns, xss (my-combination m xs)] | |
(mapcat (fn [xs'] (my-group (filter #(not-contain? % xs') xs) ms (cons xs' ys))) xss) | |
) | |
) | |
) | |
) | |
(defn my-combination | |
"Generate the combinations of K distinct objects chosen from the N elements of a list." | |
([n xs] (my-combination n xs nil)) | |
([n xs ys] | |
(if (== n 0) | |
(list (reverse ys)) | |
(mapcat | |
#(let [[z & zs] (drop % xs)] (my-combination (dec n) zs (cons z ys))) | |
(range 0 (- (count xs) (dec n))) | |
) | |
) | |
) | |
) | |
(defn not-contain? | |
[x xs] | |
(nil? (some #(= % x) xs)) | |
) |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
(defn my-lsort | |
"Sorting a list of lists according to length of sublists. (sort by length)" | |
[xss] | |
(sort-by count xss) | |
) | |
(defn my-lfsort | |
"Sorting a list of lists according to length of sublists. (sort by length frequency)" | |
[xss] | |
(mapcat #(map second (second %)) (sort-by #(count (second %)) (group-by first (map #(list (count %) %) xss)))) | |
) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment