java - Finding N Subsets of a List Object to a sum -


i trying list of subsets sum specified sum , keep running out if index. below code:

private void calcbudget(list<listinfo> data, int fromindex, int endindex, int suminstack, float target) {      apputils.log(tag, "begining: " + fromindex);     if (suminstack == target) {       apputils.log(tag, "totalsize: " + stackinfo.size());     }      (int currentindex = fromindex; currentindex < endindex; currentindex++) {       listinfo info = data.get(currentindex);       price currentprice = info.getprices().get(0);       if (suminstack + currentprice.getprice() <= target) {          stackinfo.add(data.get(currentindex));         suminstack += currentprice.getprice();          calcbudget(data, currentindex+1, endindex, suminstack, target);         price topopprice = data.get(0).getprices().get(0);         suminstack -= topopprice.getprice();         data.remove(0);       }     }   } 

and exception thrown @ last two. e.g: if length == 10 throws if currentindex == 8.

i keep getting indexoutofboundexception. after time here listinfo info = data.get(currentindex); don't know why. appreciated.

edit:

this way calling method:

calcbudget(listinfos, 0, listinfos.size() - 1, 0, 45); 

without getting details of code, doing filtered power set. 1 of classic ways calculate power set, to

  • create set of sets (or list of sets)
  • insert empty set result set
  • for each element of original collection, iterate on result set, , make copy of each of existing sets new element added them

in case, need add filter that, restricting output sets produce desired sum. here's sample implementation:

public static set<set<integer>> powersetwithsum(set<integer> source, int sum) {     set<set<integer>> result = new linkedhashset<>();     result.add(collections.<integer>emptyset());     (integer integer : source) {         set<set<integer>> tmp = new linkedhashset<>();         (set<integer> set : result) {             set<integer> copy = new linkedhashset<>(set);             copy.add(integer);              // optimization save time , space             if (copy.stream().maptoint(integer::valueof).sum() <= sum) {                 tmp.add(copy);             }         }         result.addall(tmp);     }     return result.stream()                  .filter((s) -> s.stream().maptoint(integer::intvalue).sum() == sum)                  .collect(collectors.toset()); } 

Comments