Java List First Item permutationsWithFirstElement(List listings)

Here you can find the source of permutationsWithFirstElement(List listings)

Description

permutations With First Element

License

Open Source License

Declaration

public static <T> List<List<T>> permutationsWithFirstElement(List<T> listings) throws Exception 

Method Source Code


//package com.java2s;
//License from project: MIT License 

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

public class Main {
    public static <T> List<List<T>> permutationsWithFirstElement(List<T> listings) throws Exception {
        List<T> list = new ArrayList<T>(listings);
        list.remove(0);/*ww w  . ja v  a 2s  .  c o m*/
        List<List<T>> perms = permutations(list);
        for (List<T> l : perms) {
            l.add(listings.get(0));
        }
        list = new ArrayList<T>();
        list.add(listings.get(0));
        perms.add(list);
        return perms;
    }

    public static <T> List<List<T>> permutations(List<T> listings) throws Exception {
        /*
         * String debug = "["; for (int i = 0; i < listings.size(); ++i) { debug
         * += listings.get(i).toString(); if (i < (listings.size() - 1)) { debug
         * += ", "; } } debug += "]"; System.out.println("permutations(" + debug
         * + ")");
         */

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

        if (listings.size() == 0) {
            // System.out.println("permutations return list of size 0");
            return perms;
        }

        List<T> list = new ArrayList<T>();
        list.add(listings.get(0));
        perms.add(list);

        if (listings.size() == 1) {
            // System.out.println("permutations return list of size " +
            // perms.size());
            return perms;
        }

        List<List<T>> perms2 = permutations(listings.subList(1, listings.size()));
        perms.addAll(perms2);

        for (List<T> l : perms2) {
            List<T> newList = new ArrayList<T>(l);
            newList.add(listings.get(0));
            perms.add(newList);
        }

        // System.out.println("permutations return list of size " +
        // perms.size());
        return perms;
    }
}

Related

  1. mergePreserveOrder(List first, List second)
  2. moveItemKindInFirst(final List list)
  3. nullSafeAppend(List first, List second)
  4. orderByFirstOccurenceInText(String listToOrder[], String textToParse, boolean fuzzy)
  5. orderByFuzzyFirstOccurenceInText(String listToOrder[], String textToParse)
  6. prepend(String first, List list)
  7. putFirstLast(List list)
  8. removeFirst(final List list)
  9. removeFirst(List list)