-
-
Save ckirkendall/3188614 to your computer and use it in GitHub Desktop.
Permutations of a list...
This file contains 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
object P26 extends App { | |
def combinations[T](n: Int, l: List[T]): List[List[T]] = { | |
if(l.size < n) { | |
Nil | |
} else { | |
n match { | |
case 0 => Nil | |
case 1 => l.map{List(_)} | |
case _ => combinations(n-1,l.tail).map{ l.head :: _} ::: combinations(n, l.tail) | |
} | |
} | |
} | |
println(combinations(3, List('a, 'b, 'c, 'd, 'e, 'f))) | |
} | |
//Output: | |
// List(List('a, 'b, 'c), List('a, 'b, 'd), List('a, 'b, 'e), List('a, 'b, 'f), List('a, 'c, 'd), List('a, 'c, 'e), List('a, 'c, 'f), List('a, 'd, 'e), List('a, 'd, 'f), List('a, 'e, 'f), List('b, 'c, 'd), List('b, 'c, 'e), List('b, 'c, 'f), List('b, 'd, 'e), List('b, 'd, 'f), List('b, 'e, 'f), List('c, 'd, 'e), List('c, 'd, 'f), List('c, 'e, 'f), List('d, 'e, 'f)) |
This file contains 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 permute [n lst] | |
(let [[x & l] lst] | |
(cond | |
(or (< (count lst) n) (= n 0)) () | |
(= 1 n) (map #(list %) lst) | |
:else (concat (map #(conj % x) (permute (dec n) l)) (permute n l))))) | |
(permute 3 [:a, :b, :c, :d, :e, :f]) | |
;OUTPUT | |
;((:a :b :c) (:a :b :d) (:a :b :e) (:a :b :f) (:a :c :d) (:a :c :e) (:a :c :f) (:a :d :e) (:a :d :f) (:a :e :f) (:b :c :d) (:b ;:c :e) (:b :c :f) (:b :d :e) (:b :d :f) (:b :e :f) (:c :d :e) (:c :d :f) (:c :e :f) (:d :e :f)) |
This file contains 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 permute [n l] | |
(if (< (count l) n) () | |
(case n | |
0 () | |
1 (map #(list %) l) | |
(concat (map #(conj % (first l)) (permute (dec n) (rest l))) (permute n (rest l)))))) | |
(permute 3 [:a, :b, :c, :d, :e, :f]) | |
;OUTPUT | |
;((:a :b :c) (:a :b :d) (:a :b :e) (:a :b :f) (:a :c :d) (:a :c :e) (:a :c :f) (:a :d :e) (:a :d :f) (:a :e :f) (:b :c :d) (:b ;:c :e) (:b :c :f) (:b :d :e) (:b :d :f) (:b :e :f) (:c :d :e) (:c :d :f) (:c :e :f) (:d :e :f)) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment