Monday 29 July 2013

Get all Possible nCr Combinations in Java

In below code to give the results of 1 2 3 4 5. 11 12 13 14 15 nCr combination values.


import java.util.Collections;

import java.util.Vector;



/**

 *

 * @author RajBharath

 */

public class nCrCombination{



    /**

     * @param args the command line arguments

     */

    public static void main(String[] args) {

        // TODO code application logic here

       

        int count = 5;

        Vector prev = new Vector();

        Vector my_list = new Vector();

        for(int tot_item = 0;tot_item<=count;tot_item++)

        {

            prev.add(tot_item);

            my_list.add(tot_item);

        }

        Vector prev1 = new Vector();

        for(int tot_item = 0;tot_item<=count;tot_item++)

        {

                //System.out.println("Size = "+prev.size());

                for(int k = 0;k<prev.size();k++)

                {

                    String tmp = prev.get(k).toString();



                    String tmp_val[] = tmp.split(",");

                    int start = (int)Double.parseDouble(tmp_val[tmp_val.length-1]);

                    for(int item = start+1;item<=count;item++)

                    {

                        prev1.add(tmp+","+item);

                        my_list.add(tmp+","+item);

                        System.out.println(tmp+","+item);

                    }

                }   

               

                prev.clear();

                //System.out.println("Size = "+prev1.size());

                prev.addAll(0,prev1);

                //prev = prev1;

                prev1.clear();

        }

        System.out.println("Tot size = "+my_list.size());

           

    }

   

}




Kindly Bookmark and Share it:

No comments:

Post a Comment

Related Posts Plugin for WordPress, Blogger...