⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 combination.java

📁 如何用一个通用的java程序找到任何一组java元素集(Object)的全部所有的组合集?这个私人收藏的简单程序可以做到。欢迎下载。
💻 JAVA
字号:
package util;

import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.List;

/**
 * Created by HW.
 * Date: Aug 7, 2008
 * Time: 1:23:36 AM
 * it creates a combination of a collection of elements
 */

public class Combination 
{

    private Combination()
    {
        super();
    }

    /**
     * find all combinations of any number of elements among the collection of Elements
     *
     * e.g.: List: "[a, b, c]"; return: "[ [a], [b], [c], [a, b], [a, c], [b, c], [a, b, c]]".
     *
     * @param <T>               Type of ELements
     * @param elements          the collection of Elements
     * @return                  All Combinations of the elements
     */


    public static <T extends Comparable<? super T>> List<List<T>> findCombinations(Collection<T> elements)
    {
        List<List<T>> result = new ArrayList<List<T>>();

        for (int i = 0; i <= elements.size(); i++)
            result.addAll(findCombinations(elements, i));

        return result;
    }

    /**
     * find all combinations of n elements among the collection of Elements
     *
     * e.g. 1: List "[a, b, c, d]"; n = 2; return: "[[a, b], [a, c], [a, d], [b, c], [b, d], [c, d]]".
     * e.g. 2: List "[a, b, c]" ; n = 3, return: "[[a, b, c]]"
     *
     * @param <T>               Type of ELements
     * @param elements          the collection of Elements
     * @param n                 number of Elements in the combination
     * @return                  All Combinations of n number of Elements
     */

    public static <T extends Comparable<? super T>> List<List<T>> findCombinations(Collection<T> elements, int n)
    {
        List<List<T>> result = new ArrayList<List<T>>();

        if (n == 0)
        {
            result.add(new ArrayList<T>());

            return result;
        }

        List<List<T>> combinations = findCombinations(elements, n - 1);
        for (List<T> combination: combinations)
        {
            for (T element: elements)
            {
                if (combination.contains(element))
                {
                    continue;
                }

                List<T> list = new ArrayList<T>();

                list.addAll(combination);

                if (list.contains(element))
                    continue;

                list.add(element);
                Collections.sort(list);

                if (result.contains(list))
                    continue;

                result.add(list);
            }
        }

        return result;
    }


}

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -