I don't believe this is efficient at all. I'm trying to create a faster implementation of this (preferably binary search or use of Sets perhaps), but for now this is where I'm at. I'm not sure if it's relevant, but I created a count variable just to see how many times the method was being called. It came to 577 times.
This is the "Subset Sum" algorithm, where I have to display all the subsets that add to a target sum, in this case 3165. It wasn't specifically stated that this problem was the algorithm, but I realized it was indeed the same concept.
My question is how can I know how efficient this program is, and are the method calls an indicator?
public class SubsetSumAlgorithm {
static int count = 0;
public static void main(String[] args) {
int[] array = {26, 39, 104, 195, 403, 504, 793, 995, 1156, 1673};
System.out.println("COLLECTIONS IN ARRAY THAT ADD TO 3165: ");
findCollections(array, 0, 0, 3165, "");
System.out.println("Method called " + count + " times.");//method calls
}
public static void findCollections(int[] array, int index, int currentPosition, int sum, String collection) {
count++; //<---COUNTING THE METHOD CALLS HERE
if (array.length < index || currentPosition > sum) {
return;
}
//if sum is found, add to subset
for (int i = index; i < array.length; i++) {
if (currentPosition + array[i] == sum) {
System.out.println(collection + " " + array[i]);
}
//otherwise, call the method again
else if (currentPosition + array[i] < sum) {//recursive call
findCollections(array, i + 1, currentPosition + array[i], sum, collection + " " + array[i]);
}
}
}
}
And here is the output:
COLLECTIONS IN ARRAY THAT ADD TO 3165:
26 195 793 995 1156
195 504 793 1673
Method called 577 times.