// Implementation of Dynamic Programming for the contiguous // load-balancing problem (Module 9). The code as shown is // incomplete: it only computes the optimal costs. The computation // of the actual partition itself is left as an exercise (of course). public class DynamicProgrammingLoadBalancing { static int[] dynamicProgramming (double[] taskTimes, int numProcessors) { int numTasks = taskTimes.length; // If we have enough processors, one processor per task is optimal. if (numProcessors >= numTasks) { int[] partition = new int [numTasks]; for (int i=0; ij+1 + ... + si double sum = 0; for (int m=j+1; m<=i; m++) sum += taskTimes[m]; // Use the recurrence relation. max = D[k-1][j]; if (sum > max) { max = sum; } // Record the best (over j). if (max < min) { min = max; D[k][i] = min; } } // end-innermost-for } // end-second-for // Optimal D[k][i] found. } //end-outermost-for int[] partition; // ... compute the partition itself (not shown) ... return partition; } public static void main (String[] argv) { test(); } public static void test () { // Test1: int numProcessors = 3; double[] taskTimes = {50, 23, 62, 72, 41}; System.out.println ("Test1: (optimal time: 113)"); runTest (taskTimes, numProcessors); // Test2: numProcessors = 2; double[] taskTimes2 = {50, 23, 62, 72, 41}; System.out.println ("Test2: (optimal time: 135)"); runTest (taskTimes2, numProcessors); // Test3: numProcessors = 6; double[] taskTimes3 = {50, 23, 62, 72, 41, 17, 68, 12, 19, 45}; System.out.println ("Test3: (optimal time: 76)"); runTest (taskTimes3, numProcessors); } static void runTest (double[] taskTimes, int numProcessors) { int[] partition = dynamicProgramming (taskTimes, numProcessors); double cost = cost (taskTimes, partition, numProcessors, true); System.out.println ("DYNAMICPROG: numTasks=" + taskTimes.length + " numProcessors=" + numProcessors + " Final completion time: " + cost); } static double cost (double[] taskTimes, int[] partition, int numProcessors, boolean printIt) { // Check whether too many processors were assigned. if (partition.length > numProcessors) { System.out.println ("ERROR: partition length=" + partition.length + " larger than numProcessors=" + numProcessors); System.exit(1); } // Print partition. if (printIt) { System.out.print ("Partition: "); for (int i=0; i