Java Array Empty Check getNonemptySubsets(Object[] objects)

Here you can find the source of getNonemptySubsets(Object[] objects)

Description

Gets all non-empty subsets of the given array of objects.

License

BSD License

Parameter

Parameter Description
objects array of objects

Return

all non-empty subsets

Declaration

public static Object[][] getNonemptySubsets(Object[] objects) 

Method Source Code


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

import java.util.ArrayList;

public class Main {
    /**//from  ww  w.jav  a2  s.c o m
     * Gets all non-empty subsets of the given array of objects.
     * 
     * @param objects array of objects
     * @return all non-empty subsets
     */
    public static Object[][] getNonemptySubsets(Object[] objects) {
        Object[][] subsets = getAllSubsets(objects);

        Object[][] nonempty = new Object[subsets.length - 1][];
        for (int i = 0; i < nonempty.length; i++)
            nonempty[i] = subsets[i + 1];

        return nonempty;
    }

    /**
     * Gets all subsets of the given array of objects.
     * 
     * @param objects array of objects
     * @return all subsets
     */
    public static Object[][] getAllSubsets(Object[] objects) {
        ArrayList<Object[]> subsets = new ArrayList<Object[]>();

        getAllSubsetsRec(subsets, new ArrayList<Object>(), objects, 0);

        return subsets.toArray(new Object[subsets.size()][]);
    }

    private static void getAllSubsetsRec(ArrayList<Object[]> subsets, ArrayList<Object> subset, Object[] objects,
            int i) {
        if (i == objects.length) {
            subsets.add(subset.toArray(new Object[subset.size()]));
        } else {
            ArrayList<Object> subset1 = new ArrayList<Object>();
            for (Object o : subset)
                subset1.add(o);

            ArrayList<Object> subset2 = new ArrayList<Object>();
            for (Object o : subset)
                subset2.add(o);
            subset2.add(objects[i]);

            i++;
            getAllSubsetsRec(subsets, subset1, objects, i);
            getAllSubsetsRec(subsets, subset2, objects, i);
        }
    }
}

Related

  1. areArraysEqual(byte[] arr1, byte[] arr2, boolean dontDistinctNilAndEmpty)
  2. getWithoutEmptyParams(String[] cmdarray)
  3. hasOneEmpty(String[] args)
  4. isEmpty(boolean[] values)
  5. isEmpty(byte[] array)