link mingle home | logged in as: guest | login/register| submit link


IndiaDiscuss.com : Social Bookmarkings and News Networking Site for India
interview_questions
Bookmarks
Code Snippet : Find All Combinations and nextCombination
18
Votes

Given an array {0,1,...n-1} . Find all Combinations of size m

saved under Code Snippets by interview_questions

 
import java.util.Arrays;

public class Combination {
    public Combination() {
    }


   
   boolean nextCombination(int[] inp,int n,int m){
     int nextElemToIncrement = -1;
     for (int i = m - 1; i >= 0; i--)
     {
           if (inp[i] < n - m + i){
               nextElemToIncrement=i;
               break;
           }
     }
     if(nextElemToIncrement==-1)return false;
     int i = nextElemToIncrement;
     if (i >= 0)
     {    
           inp[i] = inp[i] + 1; 
           for (int j = i + 1; j < m; j++)
               inp[j] = inp[j-1] + 1;
           return true;    
     }
     return false;   
   }
   
   public void allCombinations(int n,int m){
     int []a = new int[m];
     for (int i = 0; i <m ; i++)a[i]=i;
     while(nextCombination(a,n,m)==true){
       System.out.println(Arrays.toString(a));
      }
   }
   


    public static void main(String[] args) {
        Combination c = new Combination();
        c.allCombinations(10,5);
    }
}

comment by freebooksandarticles on 2008-06-24 04:00:25
output of n=5 m=3
[0, 1, 3]
[0, 1, 4]
[0, 2, 3]
[0, 2, 4]
[0, 3, 4]
[1, 2, 3]
[1, 2, 4]
[1, 3, 4]
[2, 3, 4]

comment by freebooksandarticles on 2008-06-24 04:01:22
 



Enter the string above
 
IndiaDiscuss | Published News | Hot
Indian Social News and Links Network
IndiaDiscuss | Published News
Indian Social News and Links Network