Original Post
Hi everyone,
I am trying to write a recurisve algoritm that, when given a list of numbers, checks to see if there is any combination of the numbers that will add up to a target value.
I'm attempting to write it using tail recursion.
The method works occasionally, but does not work every time. My problem is if I have a list {9, 7, 2, 5, 1} and the target is 11, obviously 2 and 9 will add together to become 11. BUT the way I have it written, it will add 1 + 5 (making 6). The next iteration will add the 2, making 8. After that, it will see the 7 and 9 and decide that the group does not exist. I do not see how to code it so that it can detect the 2 and 9 combination. Did that make sense?
[source lang=java]
public static boolean groupExists(final List numbers, final int target)
{
if (numbers == null || numbers.isEmpty())
{
return false;
}
else if (target == 0)
{
return true;
}
else if (numbers.size() == 1)
{
return (numbers.get(0) == target);
}
else if (target == numbers.get(numbers.size()-1))
{
return true;
}
else
{
if (target > numbers.get(numbers.size()-1))
{
return groupExists(numbers.subList(0, numbers.size()-1), target - (numbers.size()-1));
}
else
{
return groupExists(numbers.subList(0, numbers.size()-1), target);
}
}
}
[/source]
I do not see how to get the method to check ALL possible combinations.
Can anyone give me some advice? Any help will be appreciated.
Thank you.
I am trying to write a recurisve algoritm that, when given a list of numbers, checks to see if there is any combination of the numbers that will add up to a target value.
I'm attempting to write it using tail recursion.
The method works occasionally, but does not work every time. My problem is if I have a list {9, 7, 2, 5, 1} and the target is 11, obviously 2 and 9 will add together to become 11. BUT the way I have it written, it will add 1 + 5 (making 6). The next iteration will add the 2, making 8. After that, it will see the 7 and 9 and decide that the group does not exist. I do not see how to code it so that it can detect the 2 and 9 combination. Did that make sense?
[source lang=java]
public static boolean groupExists(final List
{
if (numbers == null || numbers.isEmpty())
{
return false;
}
else if (target == 0)
{
return true;
}
else if (numbers.size() == 1)
{
return (numbers.get(0) == target);
}
else if (target == numbers.get(numbers.size()-1))
{
return true;
}
else
{
if (target > numbers.get(numbers.size()-1))
{
return groupExists(numbers.subList(0, numbers.size()-1), target - (numbers.size()-1));
}
else
{
return groupExists(numbers.subList(0, numbers.size()-1), target);
}
}
}
[/source]
I do not see how to get the method to check ALL possible combinations.
Can anyone give me some advice? Any help will be appreciated.
Thank you.