Saturday, August 10, 2013

Dynamic programming - memoization - cutting a rod problem

Problem - Find best way to cut a rod of length n
    • Given: rod of length $n$
    • Assume that each length rod has a price p(i) fot length i
    • Find best set of cuts to get maximum price
      • Each cut is integer length
      • Can use any number of cuts, from 0 to n-1
      • No cost for a cut
Solution - Using dynamic bottom up to figure out optimum order to fill the solution array Or Using the recursion 

import java.util.ArrayList;

public class CutRod {

int[] cutSize = {1,2,3,4,5,6,7,8};
int[] cutCost = {1,5,8,9,10,17,17,20};
int rodSize = 8;
public static void main(String[] args) {
CutRod rod = new CutRod();
ArrayList<Integer> maxCosts = new ArrayList<Integer>();
maxCosts.add(0, 0);
rod.calculateMaxCostWithDP(maxCosts, 1);

System.out.println( "maxCost By Bottom Up DP= " + maxCosts.get(rod.rodSize )  );
System.out.println( "maxCost By Recursion=" + rod.calculateMaxCostWithRecursion(rod.rodSize));
}

private void calculateMaxCostWithDP(ArrayList<Integer> maxCosts, int size) {
if (size > rodSize )
return;
int b ;
int cost =0;
int maxCost = 0;

for(int index= 0 ; index < cutSize.length ; index++){
b = size - cutSize[index];
if ( b < 0)
continue;
cost =  maxCosts.get(b).intValue() + cutCost[index];
if ( cost > maxCost){
maxCost = cost;
}
}
maxCosts.add(size,maxCost);
calculateMaxCostWithDP(maxCosts, ++size);

}

private int calculateMaxCostWithRecursion(int size) {
if ( size < 1)
return 0;
int b ;
int cost =0;
int maxCost = 0;

for(int index= 0 ; index < cutSize.length ; index++)
{
b = size - cutSize[index];
if ( b < 0)
continue;
cost = calculateMaxCostWithRecursion(b) + cutCost[index];
if ( cost > maxCost) {
maxCost = cost;
}
}
return maxCost;
}

}

Output-

maxCost By Bottom Up DP= 22

maxCost By Recursion=22

No comments:

Post a Comment