Last active
February 22, 2016 11:15
-
-
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)
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
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