Skip to content

Instantly share code, notes, and snippets.

@cdarlint

cdarlint/combinations.java

Last active Sep 30, 2018
Embed
What would you like to do?
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;
public class arraycalc {
public static void main(String[]args){
List<Integer> arr = Arrays.asList(1,2,3,4,5);
List<Integer> c = Arrays.asList(4,5);
List<List<Integer>> result = arraycalc.combinations(arr,c,new ArrayList<Integer>(),new ArrayList<List<Integer>>());
System.out.println(result);
System.out.println(combinations(Arrays.asList("A","B","C"),Arrays.asList(2,3),new ArrayList<String>(),new ArrayList<List<String>>()));
}
public static <T> List<List<T>>combinations(List<T> arr,List<Integer> c, List<T> cut, List<List<T>> results){
if (c.contains(0)){
List<T>cut3=new ArrayList<T>(cut);
results.add(cut3);
if(c.stream().map(x -> x>0).count()==0) {
return results;
}
}
for(int i=0;i<arr.size();i++){
List<T> arr2=arr.stream().skip(i+1).collect(Collectors.toList());
List<T> cut2 = new ArrayList<T>(cut);
List<Integer> c2=c.stream().map(x->x-1).collect(Collectors.toList());
cut2.add(arr.get(i));
results=combinations(arr2,c2,cut2,results);
}
return results;
}
}
// OUTPUT
// [[1, 2, 3, 4], [1, 2, 3, 4, 5], [1, 2, 3, 5], [1, 2, 4, 5], [1, 3, 4, 5], [2, 3, 4, 5]]
// [[A, B], [A, B, C], [A, C], [B, C]]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment