logo CodeStepByStep logo

isMeasurable

Language/Type: Java recursion backtracking
Related Links:

Write a recursive method named isMeasurable that determines whether it is possible to weigh out exactly a given amount on two scales, given a target amount and a collection of weights to use. Your method accepts two parameters: a list of integers representing weights that you can use, and an integer target weight amount.

For example, suppose that you have only two weights: a 1-ounce weight and a 3-ounce weight. With these you can easily measure out 4 ounces by placing both weights on one side of the scale, as shown:

figure

You can also measure out 2 ounces by shifting the 1-ounce weight to the other side, as follows:

figure

Suppose that the variable weights has been initialized as follows:

List<Integer> weights = new ArrayList<>();
weights.add(1);
weights.add(3);

Given these values, the calls of isMeasurable(weights, 4) and isMeasurable(weights, 2) would both return true. On the other hand, the call of isMeasurable(weights, 5) would return false because it is impossible to use the 1- and 3-ounce weights to add up to 5 ounces. You don't need to use every weight in the list to reach the given target; in the example above, calls of isMeasurable(weights, 3) and isMeasurable(weights, 1) would return true because you can make those amounts by using only a single weight in each case.

If the target weight passed is 0, your method should always return true. You may assume that the value of the target weight passed will not be initially negative, and that the list passed does not contain any negative weight values in it.

Constraints: You may use a loop in your solution if you like, but the overall algorithm must use recursion and backtracking. You may define helper methods if you like.

Method: Write a Java method as described, not a complete program or class.

You must log in before you can solve this problem.

Log In

Need help?

Stuck on an exercise? Contact your TA or instructor.

If something seems wrong with our site, please

Is there a problem? Contact us.