Main.java Source code

Java tutorial

Introduction

Here is the source code for Main.java

Source

//package com.java2s;
import java.util.ArrayList;

import java.util.Collections;

import java.util.List;

public class Main {
    public static <T extends Comparable<? super T>> List<List<T>> getAllCombinations(final List<T> pList,
            final int pSize) {
        assert (pSize < pList.size());
        final List<List<T>> result = new ArrayList<List<T>>();

        if (pSize == 0) {
            result.add(new ArrayList<T>());
            return result;
        }

        final List<List<T>> combinations = getAllCombinations(pList, pSize - 1);
        for (final List<T> combination : combinations) {
            for (final T element : pList) {
                if (combination.contains(element)) {
                    continue;
                }

                final 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;
    }

    public static <T> List<List<T>> getAllCombinations(final List<T> pList) {
        final List<List<T>> result = new ArrayList<List<T>>(pList.size());
        // if it has only one element, the resulting list
        // is a list with the single element
        if (pList.size() == 1) {
            final List<T> temp = new ArrayList<T>();
            temp.add(pList.get(0));
            result.add(temp);
        } else {
            for (final T element : pList) {
                // create a new sublist
                final List<T> temp = new ArrayList<T>(pList);
                // remove the current item
                temp.remove(element);
                // get the all combinations for the sublist
                final List<List<T>> sublist = getAllCombinations(temp);
                for (final List<T> item : sublist) {
                    item.add(element);
                }

                result.addAll(sublist);
            }
        }

        return result;
    }
}