Vous êtes sur la page 1sur 3

//FIRST D1 ARRANGE IN ASCENDING ORDER

//THE ALGORITHM HANGS FOR ZERO ANY INPUTS,SO FILTER OUT THE ZEROES IN THE MAIN LOOP

import java.io.*;
import java.util.*;
class SumHunt
{
public static int n=12,cnt=0,SUM=0;
public static int D1[]=new int[n];
String BL="",LL=""; //A summing list of positions

public boolean bingo=false;

/////THIS BELOW IS THE CORE FUNCTION////////

void searchSum(int sum,int p) //a search starting from position 'p'


in D1
{
BL=Integer.toString(D1[p])+"+"+BL;
if(sum==D1[p]) //IS THE LIST COMPLETE?
{
cnt++;
bingo=true;
if(!BL.equals(LL))
{
System.out.println(SUM+" = "+BL);
LL=BL;
} //print the list,avoids duplicate strings,since we just hit
the target sum
}
else if(p<n&&D1[p]<sum) //OR DO WE KEEP BUILDING THE LIST?
{
for(int k=1;k<(n-p);k++) //OK,THEN CALL FOR RECURSION IN THE
NEXT CELL
{
searchSum(sum-D1[p],p+k);
if(bingo)
{bingo=false;continue;} //IF WE SUCCEED IN NEXT-CELL-
CHAIN,RESET
} //BINGO STATUS & CONTINUE
}
BLCutLast(); //Removes last entry in our list
}

////////THE OTHER FUNCTIONS ARE AUXILIARIES/////////

void BLCutLast()
{
while(true)
{
BL=BL.substring(1); //Cuts away the first character
if(BL.charAt(0)=='+') //Once you encounter the plus sign,delete that
too and stop
{
BL=BL.substring(1);
break;
}
}
}

void sortArray()
{
int i=0,j=0,t=0;
for(i=0;i<n;i++)
{
for(j=0;j<n-i-1;j++)
{
if(D1[j]>D1[j+1])
{
t=D1[j];
D1[j]=D1[j+1];
D1[j+1]=t;
}
}
}
}

public static void main()


{
SumHunt Sum_Hunter=new SumHunt();

Scanner sc=new Scanner(System.in);


System.out.println("Enter number array(12 nos.,ascending order)");

int i=0; //a counter for loops


int a=0; //for temporary storage
for(i=0;i<12;i++)
{
D1[i]=sc.nextInt();
}
Sum_Hunter.sortArray();

System.out.println("Enter target sum");


int sum=sc.nextInt();
i=0;
while(D1[i]==0){i++;} //traverses to the end of any zeroes
for(;i<n;i++) //n=12 here
{
if(D1[i]==a){continue;}
//no need for an else here since continue would
skip it anyway
SUM=sum;
Sum_Hunter.searchSum(sum,i); //Search for sum with min. no
as D1[i]
System.out.println("Groupings with min. no. as "+D1[i]+"-->count
="+cnt);
cnt=0; //reset the count

a=D1[i]; //Stores for comparison in next cycle to avoid


repeating for same number
}
//Obj.searchSum(7,1);
//System.out.println("-->count ="+cnt);
System.out.println("The read & sorted array was : ");
for(i=0;i<n;i++) //READS OUT THE ARRAY FOR DEBUGGING
{
System.out.print(" , "+D1[i]);
}
}
}

Vous aimerez peut-être aussi