Friday, December 23, 2011

find all the possible subset of the array of size k

Given an array of size n, find all the possible sub set of the array of size k(all the subsets must be of size k).


Algorithm:
Suppose array size is of length 5 ie A = {1,2,3,4,5};
and we need all the subsets of size k=3.


If we were supposed to find all the subsets then we would have taken all the binary representations of numbers from 1 to (2^5 - 1) and then according to the bits set, we would have chosen the corresp. number from Array A.


Now the idea is get the minimum number where all "k" lower bits are set.
In our case that would be = "00111" => 7 in decimal
Now find the next decimal number > 7 where 3 bits are set.
Keep on finding the next numbers till you hit "11100" = 28 since that is the largest binary number with 3 bits set of length 5.


Given an integer, method to find the next smallest number that have the same numbers of bits set:
1. Traverse from right to left, Once we have passed a 1, turn on the next 0. 
ex: 101110 becomes 111110
2. Turn off the one that's just to the right side of that (where you switched on '0' to '1').
now 111110 becomes 110110.
3. Make the number as small as possible by rearranging all the 1's to be as far as right as possible.
ex: 110110 becomes 110011.


Sample output of below code:

Subsets of size 3 are: 
3 4 5 
2 4 5 
2 3 5 
2 3 4 
1 4 5 
1 3 5 
1 3 4 
1 2 5 
1 2 4 
1 2 3 






No comments:

Post a Comment