【Java.算法】从数组中选择有限个数的组合器Combiner

【代码】

import java.util.ArrayList;
import java.util.List;

/**
 * 从数组中选择有限个数的组合器
 * 比如从abc中选2个,会产生ab,ac,bc的结果
 */
public class Combiner {
    /**
     * 选择的结果
     */
    private List<List<String>> results;
    
    /**
     * 构造函数
     * @param candidates 候选者名单
     * @param selectCnt 选择的数量
     */
    public Combiner(String[] candidates,int selectCnt) {
        int nCnt = candidates.length;
        
        if(selectCnt>nCnt) {
            throw new ArrayIndexOutOfBoundsException(selectCnt+">"+nCnt);
        }
        
        results=new ArrayList<>();

        int nBit = (0xFFFFFFFF >>> (32 - nCnt));

        for (int i = 1; i <= nBit; i++) {
            List<String> ls=new ArrayList<>();
            
            for (int j = 0; j < nCnt; j++) {
                if ((i << (31 - j)) >> 31 == -1) {
                    ls.add(candidates[j]);
                }
            }

            if(ls.size()==selectCnt) {
                results.add(ls);
            }
        }
    }
    
    /**
     * 取得选择的结果
     * @return
     */
    public List<List<String>> getResults(){
        return results;
    }
    
    /**
     * 使用示例
     * @param args
     */
    public static void main(String[] args) {
        String[] arr= {"A","B","C"};
        Combiner c=new Combiner(arr,2);
        
        List<List<String>> results=c.getResults();
        for(List<String> ls:results) {
            System.out.println(ls);
        }
    }
}

 

【输出】

[A, B]
[A, C]
[B, C]

 

【参考资料】

https://www.jianshu.com/p/a6e3c980e932

END

posted @ 2022-12-12 23:10  逆火狂飙  阅读(17)  评论(0编辑  收藏  举报
生当作人杰 死亦为鬼雄 至今思项羽 不肯过江东