Last active
August 29, 2015 14:01
-
-
Save sshark/3eaad0a6bc0a4b93334f to your computer and use it in GitHub Desktop.
Combinations polygots
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
| // Ruby | |
| [-15,10,4,-3,5,-7,1,-5].reduce([[]]) {|ll, l| ll + ll.map{|a| a + [l]}}.select{|l| l.inject(:+) == 0} | |
| // (Scala (functions) | |
| List(-15,10,4,-3,5,-7,1,-5).foldLeft(List(List[Int]())){ (ll,l) => ll ++ ll.map{l :: _}}.filter(!_.isEmpty).filter(_.sum == 0) | |
| // Scala (recursion) | |
| def combi[A](l : List[A]) : List[List[A]] = { | |
| def _combi(k : List[A], ll : List[List[A]]) : List[List[A]] = { | |
| if (k.isEmpty) ll | |
| else _combi(k.tail, __combi(k.head, ll, ll)) | |
| } | |
| def __combi(a : A, la : List[List[A]], result : List[List[A]]) : List[List[A]] = { | |
| if (la.isEmpty) result | |
| else __combi(a, la.tail, (a :: la.head) :: result) | |
| } | |
| _combi(l, List(List.empty[A])) | |
| } | |
| combi(List(1,2,3)) | |
| combi(List(1,2,3,4,5)).size | |
| // Clojure | |
| (reduce (fn [x y] (into x (map (fn [z] (cons y z)) x))) '(()) '(1 2 3 1)) | |
| (count (reduce (fn [x y] (into x (map (fn [z] (cons y z)) x))) '(()) '(1 2 3 1))) | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment