import java.util.Random; /** * A class to measure the running time of all solutions to * the Stock Market problem. * * @author americachambers * */ public class SubsetTester { private static final int MAX_VALUE = 10000; private static final int NUM_DAYS_LENGTH = 20; private static final int BURN_IN = 50; private static Random rng = new Random(); /** * Populates prices array with randomly chosen prices * @param array */ public static void populatePrices(int[] array) { for(int i = 0; i < array.length; i++) { array[i] = rng.nextInt(MAX_VALUE)+1; } } /** * Takes an instance of the Stock Market problem and transforms it into * an instance of the Subset Sum problem * @param array An array of stock prices * @return An array of integers (i.e. difference in price of consecutive days) */ public static int[] transformProblem(int[] array){ int[] newArray = new int[array.length-1]; // Transform the problem into an instance of the // Maximum subarray problem for(int i = 0; i < array.length-1; i++) { newArray[i] = array[i+1]-array[i]; } return newArray; } public static void main(String[] args) { // Consider different number of days ranging from 2 to 1024 days int[] num_days = new int[NUM_DAYS_LENGTH]; num_days[0] = 2; for(int i = 1; i < num_days.length; i++){ num_days[i] = num_days[i-1]*2; } // Instantiate the 3 algorithms we are comparing SubsetIfc[] algorithms = new SubsetIfc[2]; algorithms[0] = new BruteForce(); algorithms[1] = new Recursive(); // Repeatedly call, but do not time, to force Java // to compile to native code (i.e. forced optimization) int[] prices = new int[100]; for(int i = 0; i < BURN_IN; i++) { populatePrices(prices); for(int j = 0; j < algorithms.length; j++){ algorithms[j].solve(prices); } } System.out.println("Finished burn in..."); // Start the actual timed trials // For each number of days // For 10 iterations // Randomly sample new prices // Run each of the 3 algorithms long[] times = new long[algorithms.length]; SubsetInfo[] solutions = new SubsetInfo[algorithms.length]; long start, end; int timedIterations = 10; for(int i = 0; i < num_days.length; i++) { prices = new int[num_days[i]]; for(int j = 0; j < timedIterations; j++){ populatePrices(prices); int[] newArray = transformProblem(prices); // Run and time each algorithm for(int k = 0; k < algorithms.length; k++){ start = System.nanoTime(); solutions[k] = algorithms[k].solve(newArray); end = System.nanoTime(); times[k] += (end - start); } // Check all answers for(int k = 1; k < algorithms.length; k++){ assert(solutions[k-1].sum == solutions[k].sum); } } // Print out the time in microseconds System.out.print(num_days[i] + "\t"); for(int k = 0; k < times.length; k++){ System.out.print((times[k]/1000)/timedIterations+ "\t"); } System.out.println(); } } }