1 year ago
#368836
aksak
Java program of the Backtracking algorithm for the Sum-of-Subsets problem
I'm currently working on a problem where I'm supposed to implement in Java the backtracking algorithm of the sum-of-subset.
Backtracking is used to solve problems in which a sequence of objects is selected from a specified set so that the sequence satisfies some criteria. In this assignment, you are expected to apply the Backtracking algorithm for the Sum-of-Subsets problem, which is explained as follows:
⢠Problem: Given n positive integers (weights) and a positive integer W, determine all combinations of the integers that sum to W.
⢠Inputs: Positive integer n, sorted (non-decreasing order) array of positive integers w indexed from 1 to n, and a positive integer W.
⢠Outputs: all combinations of the integers that sum to W.
Following our usual convention, n, w, W, and include are not inputs to our routines. If these variables were defined globally, the top-level call to sum_of_subsets would be as follows:
sum_of_subsets(0, 0, total);
the algorithm included in the book:
void sum_of_subsets(index i,
int weight, int total) {
if (promising(i))
if (weight == W)
cout << include[1] through include [i];
else {
include[i + 1] = "yes"; // Include w[i + 1].
sum_of_subsets(i + 1, weight + w[i + 1], total - w[i + 1]);
include[i + 1] = "no"; // Do not include w[i + 1].
sum_of_subsets(i + 1, weight, total - w[i + 1]);
}
}
bool promising (index i); {
return (weight + total >= W) && (weight == W || weight + w[i + 1] <= W);
}
I have tried to implement the above algorithm using Java but it's not working
public class Backtracking {
//public static boolean include[];
public static int W = 52;
public static int w[] = { 2, 10, 13, 17, 22, 42 };
public static boolean include[] = new boolean[50];
public static void main(String[] args) {
// TODO Auto-generated method stub
System.out.println("solution: ");
for(int i=0; i<w.length-1;i++) {
sum_of_subsets(i, w[i], W);
}
}
public static void sum_of_subsets(int i, int weight, int total) {
if (promising(i, weight, total)) {
if (weight == W) {
for (int j = 0; j < w.length; j++) {
if(include[j])
System.out.println(w[j]);
}
} else {
include[i + 1] = true;
sum_of_subsets(i + 1, weight + w[i + 1], total - w[i + 1]);
include[i + 1] = false;
sum_of_subsets(i + 1, weight, total - w[i + 1]);
}
}
}
public static boolean promising(int i, int weight, int total) {
return (weight + total >= W) && (weight == W || weight + w[i+1] <= W);
}
}
the output i get is wrong i get {17,22} instead of subsets that sums up to 52 like {42,10} , {17,13,22} etc
java
algorithm
backtracking
recursive-backtracking
0 Answers
Your Answer