0

Given an array of n numbers, how can we calculate the subsets of that array (0 based indexed) in a given range i.e starting from ith index to jth index. I tried using bitmasking but couldn't figure out how to solve this because of the range.

For example, if array a is a = [2 6 9 1 7] and the given range is 1 to 3, then the answer will be = [6], [9], [1], [6 9], [6 1], [9 1], [6 9 1]

Here is the function which calculates all the subsets of array and I'm unsure how to use that range constrain.

private static void findSubsets(int array[])
{
    int numOfSubsets = 1 << array.length; 

    for(int i = 0; i < numOfSubsets; i++)
    {
        int pos = array.length - 1;
        int bitmask = i;

        System.out.print("{");
        while(bitmask > 0)
        {
            if((bitmask & 1) == 1)
            System.out.print(array[pos]+",");
            bitmask >>= 1;
            pos--;
        }
        System.out.print("}");
    }
}
styvane
  • 59,869
  • 19
  • 150
  • 156
ashwani
  • 690
  • 3
  • 16

1 Answers1

0

If your current implementation of findSubSets works, then converting to a range is almost trivial. Just include an offset index equal to i and change array.length to j - i + 1.

   private static void findSubsets(int array[], int i, int j)
   {
      int arrayLen = j - i + 1;
      int numOfSubsets = 1 << (arrayLen - 1);

      for (int k = 1; k < numOfSubsets; k++)
      {
         int pos = j;
         int bitmask = k;

         System.out.print("{");
         while (bitmask > 0)
         {
            if ((bitmask & 1) == 1)
               System.out.print(array[pos] + ",");
            bitmask >>= 1;
            pos--;
         }
         System.out.print("}");
      }
   }
  • hey is there any better algorithm than bitmasking? I have to use this function repeatedly and this seems inefficient to me. Btw, thanks for the help. – ashwani Apr 05 '16 at 14:32
  • @user bitmasking is pretty good already... AFAIK the only other way is some sort of recursive, dynamic-programming way to calculate all subsets –  Apr 05 '16 at 15:05