使用guava 12 Collections2.permutations(),我想知道是否可以限制排列的大小?
更准确地说,我想在n个元素的列表中获得k个大小的排列列表,而不是获得所有n个大小的排列的列表.
目前,如果我传递4个水果的列表,那么permutations()将返回24个4大小排列的列表,尽管我只对检索4个唯一大小3个排列感兴趣.
说我有4个水果的清单:
["Banana","Apple","Orange","Peach"]
如果我只对3号排列感兴趣,我希望返回以下内容:
["Banana","Orange"] ["Banana","Peach"] ["Banana","Peach"] ["Apple","Peach"]
解决方法
此代码计算出变体,然后在每个唯一的3组上运行排列.
即对于“A”,“B”,“C”,“D”,可能性为[[A,B,C],[A,D],C,[B,d].然后我们计算每个三人组(或n-some)的排列,并将可能性附加到列表中.
PermutationsOfN.processSubsets(List set,int k)返回:
[[A,D]]
更进一步PermutationsOfN.permutations(List list,int size)返回:
[[A,B],[C,A,A],[ A,D,[D,D]]
import java.util.Collection; import java.util.List; import com.google.common.collect.Collections2; import com.google.common.collect.ImmutableList; import com.google.common.collect.Lists; public class PermutationsOfN<T> { public static void main( String[] args ) { List<String> f = Lists.newArrayList( "A","B","C","D" ); PermutationsOfN<String> g = new PermutationsOfN<String>(); System.out.println( String.format( "n=1 subsets %s",g.processSubsets( f,1 ) ) ); System.out.println( String.format( "n=1 permutations %s",g.permutations( f,1 ) ) ); System.out.println( String.format( "n=2 subsets %s",2 ) ) ); System.out.println( String.format( "n=2 permutations %s",2 ) ) ); System.out.println( String.format( "n=3 subsets %s",3 ) ) ); System.out.println( String.format( "n=3 permutations %s",3 ) ) ); System.out.println( String.format( "n=4 subsets %s",4 ) ) ); System.out.println( String.format( "n=4 permutations %s",4 ) ) ); System.out.println( String.format( "n=5 subsets %s",5 ) ) ); System.out.println( String.format( "n=5 permutations %s",5 ) ) ); } public List<List<T>> processSubsets( List<T> set,int k ) { if ( k > set.size() ) { k = set.size(); } List<List<T>> result = Lists.newArrayList(); List<T> subset = Lists.newArrayListWithCapacity( k ); for ( int i = 0; i < k; i++ ) { subset.add( null ); } return processLargerSubsets( result,set,subset,0 ); } private List<List<T>> processLargerSubsets( List<List<T>> result,List<T> set,List<T> subset,int subsetSize,int nextIndex ) { if ( subsetSize == subset.size() ) { result.add( ImmutableList.copyOf( subset ) ); } else { for ( int j = nextIndex; j < set.size(); j++ ) { subset.set( subsetSize,set.get( j ) ); processLargerSubsets( result,subsetSize + 1,j + 1 ); } } return result; } public Collection<List<T>> permutations( List<T> list,int size ) { Collection<List<T>> all = Lists.newArrayList(); if ( list.size() < size ) { size = list.size(); } if ( list.size() == size ) { all.addAll( Collections2.permutations( list ) ); } else { for ( List<T> p : processSubsets( list,size ) ) { all.addAll( Collections2.permutations( p ) ); } } return all; } }