logo CodeStepByStep logo

rodCutting

Language/Type: Java backtracking return
Related Links:

Write a recursive method named rodCutting that solves the classic "rod cutting" problem using backtracking. The idea is that you are given a rod that can be cut into pieces of various sizes and sold, where each piece fetches a given price in return, and you are trying to find the optimal way to cut the rod to generate the greatest total price. For example, suppose you have a rod as shown in the following figure that can be cut into pieces of length 1-8:

length       1   2   3   4   5   6   7   8
rod       =================================
price        1   5   8   9  10  17  17  20

Your method accepts a list of integers representing the various sizes that can be cut, from 1 through the length of the rod inclusive. For the rod in the preceding figure, the list would contain the values {1, 5, 8, 9, 10, 17, 17, 20}. You should return an integer representing the maximum sum that can be obtained by cutting the rod into pieces of any length. For the rod in the preceding figure, the correct answer is to return 22, which is obtained by cutting the rod into pieces of lengths 2 and 6.

You are allowed to modify the list passed in as the parameter as you compute the answer, as long as you restore it to its original form by the time the overall call is finished. You may use loops in solving this problem, but your overall algorithm should utilize recursive backtracking.

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.