Ask Question

Name:
Title:
Your Question:

Answer Question

Name:
Your Answer:
User Submitted Source Code!


Description:
  sum
Language: JAVA
Code:
import java.util.*;
class SumOfSubsets
{
            static int w[],x[],i,j,s=0,k=1,r=0,m,n;
            void read()
            {
                        Scanner s=new Scanner(System.in);
                        System.out.println("Plaese enter the number of values");
                        n=s.nextInt();
                        w=new int[n+1];
                        x=new int[n+1];
                        System.out.println("Plaese enter the corresponding weights");
                        for(i=1;i<=n;i++)
                        {
                                    System.out.println("Please enter the weight");
                                    w[i]=s.nextInt();
                                    r+=w[i];
                                    x[i]=0;
                        }
                        System.out.println("Please enter the total sum");
                        m=s.nextInt();
            }
            void sumOfSubset(int s,int k, int r)
            {
                        if(s+w[k]==m)
                                    {
                                    x[i]=1;
                                    System.out.println("Possible Solutions are");
                                    for(i=1;i<=n;i++)
                                                System.out.print(" "+x[i]);
                                    System.out.println();
                                    }
                        else if(s+w[k]+w[k+1]<=m)
                                    {
                                                x[k]=1;
                                                sumOfSubset(s+w[k],k+1,r-w[k]);
                                    }
                        if((s+r-w[k]>=m)&&(s+w[k+1]<=m))
                                    {
                                                x[k]=0;
                                                sumOfSubset(s,k+1,r-w[k]);
                                    }
            }
            public static void main(String args[])
            {
                        SumOfSubsets ss=new SumOfSubsets();
                        ss.read();
                        ss.sumOfSubset(s,k,r);
            }
}
          
Comments: