Skip to content

Commit

Permalink
Making public the combinationSet in Combinatorics.
Browse files Browse the repository at this point in the history
  • Loading branch information
datumbox committed Sep 26, 2016
1 parent c7aa388 commit 0600fe3
Showing 1 changed file with 24 additions and 16 deletions.
Expand Up @@ -19,27 +19,27 @@

/**
* Utility class for combinations and permutations.
*
*
* @author Vasilis Vryniotis <bbriniotis@datumbox.com>
*/
public class Combinatorics {

/**
* Returns the permutations of a collection.
* Ported from:
* http://stackoverflow.com/questions/10503392/java-code-for-permutations-of-a-list-of-numbers
*
*
* @param <T>
* @param elements
* @return
* @return
*/
public static <T> Collection<List<T>> permutations(Collection<T> elements) {
Collection<List<T>> result = new ArrayList<>();
if (elements.isEmpty()) {
result.add(new LinkedList<>());
return result;
}

List<T> rest = new LinkedList<>(elements);
T head = rest.remove(0);
for (List<T> permutations : permutations(rest)) {
Expand All @@ -54,40 +54,48 @@ public static <T> Collection<List<T>> permutations(Collection<T> elements) {
}
return result;
}

/**
* Returns all the possible combinations of a list.
* Ported from:
* http://codereview.stackexchange.com/questions/26854/recursive-method-to-return-a-set-of-all-combinations
*
*
* @param <T>
* @param elements
* @param elementCount
* @return
* @return
*/
public static <T> Collection<List<T>> combinations(List<T> elements, int elementCount) {
Set<Set<T>> combinations = getCombinationsFor(elements, elementCount);
Set<Set<T>> combinations = combinationsSet(elements, elementCount);

Collection<List<T>> result = new ArrayList<>();
for(Set<T> linkedset : combinations) {
result.add(new ArrayList<>(linkedset));
}

return result;
}

private static <T> Set<Set<T>> getCombinationsFor(List<T> group, int subsetSize) {

/**
* Similar to combinations() method it returns all possible combinations in a set.
*
* @param group
* @param subsetSize
* @param <T>
* @return
*/
public static <T> Set<Set<T>> combinationsSet(List<T> group, int subsetSize) {
Set<Set<T>> resultingCombinations = new LinkedHashSet<> ();
int totalSize=group.size();
if (subsetSize == 0) {
resultingCombinations.add(new LinkedHashSet<>());
}
}
else if (subsetSize <= totalSize) {
List<T> remainingElements = new ArrayList<> (group);
T X = remainingElements.remove(remainingElements.size()-1);

Set<Set<T>> combinationsExclusiveX = getCombinationsFor(remainingElements, subsetSize);
Set<Set<T>> combinationsInclusiveX = getCombinationsFor(remainingElements, subsetSize-1);
Set<Set<T>> combinationsExclusiveX = combinationsSet(remainingElements, subsetSize);
Set<Set<T>> combinationsInclusiveX = combinationsSet(remainingElements, subsetSize-1);
for (Set<T> combination : combinationsInclusiveX) {
combination.add(X);
}
Expand Down

0 comments on commit 0600fe3

Please sign in to comment.