Skip to content

Instantly share code, notes, and snippets.

@lwld
Last active February 22, 2016 11:15
Show Gist options
  • Save lwld/4937cc6a5c98b1e07a6f to your computer and use it in GitHub Desktop.
Save lwld/4937cc6a5c98b1e07a6f to your computer and use it in GitHub Desktop.
Permutations of a certain length of a list (combinations, choose k of n, unordered) (v2)
import com.google.common.collect.Lists;
import java.util.List;
public class ListPermutation {
public static void main(String[] args) {
for (int i = 0; i <= 6; i++) {
System.out.println("Take " + i + " of 5: " + permutations(Lists.newArrayList(1, 2, 3, 4, 5), i));
}
System.out.println("Take 1 of 1: " + permutations(Lists.newArrayList(1), 1));
System.out.println("Take 1 of 0: " + permutations(Lists.newArrayList(), 1));
}
public static <T> List<List<T>> permutations(List<T> input, int select) {
List<List<T>> res = Lists.newArrayList();
if (select == 0) {
res.add(Lists.<T>newArrayList());
return res;
}
for (int i = 1; i < input.size(); i++) {
T current = input.get(i);
List<T> subListBeforeCurrent = input.subList(0, i);
for (List<T> permutation : permutations(subListBeforeCurrent, select - 1)) {
permutation.add(current);
res.add(permutation);
}
}
return res;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment