Thursday, April 3, 2014

Partitions of a number in java

This application generates the partitions of a number. For example, for no. 3 will display:
1 1 1
1 2
2 1

-------------------------------------------------------------------------------------------------------------
import java.io.*;
public class partitii_nr {
private static int[] sol=new int[20];
private static int n,i,s;
private static void back(int k){
if(s==n){
for(i=1;i<k;i++)
System.out.print(sol[i]+" ");
System.out.println("");
}
else{
sol[k]=0;
for(i=1;sol[k]+s<n;i++){
sol[k]++; s+=sol[k]; back(k+1);s-=sol[k];
}

}
}
public static void main(String[] args){
try{
BufferedReader input=new BufferedReader(new InputStreamReader(System.in));
System.out.println("Input number:");
n=Integer.parseInt(input.readLine());
back(1);
}catch(Exception e){e.printStackTrace();}
}
}
-------------------------------------------------------------------------------------------------------------

Related Posts by Categories

0 comments:

Post a Comment