Lifts are usually limited in capacity, both in space (persons) as in load (kgs). Imagine we have a small lift which is capable of transporting a maximum of 6 persons and a maximum load of 500kg. Suppose 13 people are waiting with the following weights: 10, 30, 40, 41, 80, 90, 50, 55, 92, 66, 82, 62 and 70kg. Write a recursive program that finds a group of people that does not exceed the maximum capacities, but has the maximum possible load in kg. (Hint: there is a valid solution that exceeds 470kg)
public static void main (String[] Args)
{
ArrayList<Integer> s = new ArrayList<Integer>(); //List of unexplored
int[] weight0 = { 10, 30, 40, 41, 80, 90, 50, 55, 92, 66, 82, 62,70}; //Initial state
int target = 500; //Goal state
System.out.println(liftGroup(weight0,0,target, s) + " way(s)"); //Recursive function
}
static int liftGroup (int[] weight,int c,int target, ArrayList<Integer> s){
assert weight != null : "array should be initialized";
assert c >= 0 && c <= weight.length;
assert s != null : "ArrayList should be initialized";
int sumOfUntried = 0;
if (c > 6) {
showSoulution(s);
return 1;
}
else if (target < 0) {
return 0;
}
else if (c >= weight.length) { //that's okay?
return 0;
}
int min = weight[c];
for (int i = c; i < weight.length; i++) {
sumOfUntried += weight[i];
if(weight[i]<min)
min=weight[i];
}
if(min>target) // If you find one BIG fatty
{
return 0;
}
if (sumOfUntried > target) { //Correct
return 0;
}
else {
s.add(weight[c]);
int with = liftGroup(weight, c + 1, target - weight[c], s);
s.remove(s.size() - 1);
int without = liftGroup(weight, c + 1, target, s);
return with + without;
}
}
/*
* Prints the ArrayList with the solution
*/
private static void showSoulution(ArrayList<Integer> s)
{
assert s != null : "ArrayList should be initialized";
System.out.println("Solution: " + s);
}}
My problem is understanding and using the base case:
- When the number of persons does not exceed the maximum limits. You've got a solution.
- But how do I comply with the two goals?