Created
October 28, 2011 14:32
-
-
Save avanwieringen/1322406 to your computer and use it in GitHub Desktop.
Combinations in Java
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
package nl.falcon108; | |
import java.util.ArrayList; | |
import java.util.List; | |
public class Collections { | |
/** | |
* Creates 2-dimensional ArrayList from a List with all the combinations of length k | |
* @param collection | |
* @param k | |
* @return 2-dimensional ArrayList with combinations | |
*/ | |
public static <T> ArrayList<ArrayList<T>> combinations(List<T> collection, int k) { | |
ArrayList<ArrayList<T>> comb = new ArrayList<ArrayList<T>>(); | |
ArrayList<ArrayList<T>> chCombs; | |
ArrayList<T> temp; | |
for(int i = 0; i < collection.size() - k + 1; i++) { | |
if(k > 1) { | |
chCombs = combinations(collection.subList(i + 1, collection.size()), k - 1); | |
for(ArrayList<T> c : chCombs) { | |
temp = new ArrayList<T>(c); | |
temp.add(0, collection.get(i)); | |
comb.add(temp); | |
} | |
} else { | |
temp = new ArrayList<T>(); | |
temp.add(collection.get(i)); | |
comb.add(temp); | |
} | |
} | |
return comb; | |
} | |
/** | |
* Creates an ArrayList with all the unique values from a List | |
* @param collection | |
* @return ArrayList with unique values | |
*/ | |
public static <T> ArrayList<T> unique(List<T> collection) { | |
ArrayList<T> unique = new ArrayList<T>(); | |
for(T t : collection) { | |
if(!unique.contains(t)) { | |
unique.add(t); | |
} | |
} | |
return unique; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment