import java.util.Arrays; /** * A greedy solution to the hiking problem * @author alchambers * */ public class Hiking { /** * A correct greedy solution for the Hiking problem * @param distances * @param maxDist * @return */ public static boolean[] greedySolution(int[] distances, int maxDist){ // This array will hold true if we stop at a particular site, and false otherwise boolean[] willStop = new boolean[distances.length]; // Initialization int curr = 0; int next = 1; int distRemain = maxDist; // Greedy choice is to go as far as we can each day while(next < distances.length){ // If we can go farther, then go if(distances[next]-distances[curr] <= distRemain){ distRemain -= (distances[next] - distances[curr]); curr = next; next = curr+1; } // Otherwise, stop for the night else{ willStop[curr] = true; distRemain = maxDist; } } willStop[willStop.length-1] = true; // the last site is our final destination return willStop; } public static void main(String[] args){ int[] distances = {0, 7, 11, 15, 16, 17, 20, 24, 30}; System.out.println("Distances:"); System.out.println(Arrays.toString(distances)); System.out.println("Able to hike 8 miles a day:"); System.out.println(Arrays.toString(greedySolution(distances, 8))); System.out.println("\nAble to hike 15 miles a day:"); System.out.println(Arrays.toString(greedySolution(distances, 15))); } }