woonie

Knapsack.java

Mar 28th, 2012
125
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.68 KB | None | 0 0
  1. import java.util.*;
  2. class Result {
  3.     // declare the member field
  4.  private int[] myBag;
  5.  private int length;
  6.     // declare the constructor
  7.  public Result(int[] bag){
  8.   myBag = bag;
  9.   length = myBag.length;
  10.  }
  11.  /**
  12.   * solve   : to count the number of sets of items satisfying the criteria.
  13.   *          (the total weight of all items in a set should not exceed the capacity of the sack)
  14.   *  Pre-condition   : myBag exists
  15.   *  Post-condition  : returns number of solutions given the capacity
  16.   */
  17.  // you should determine the recurrence state(parameters) yourself.
  18.  public int solve(int remWeight, int currentCount) {
  19.   // implementation
  20.   int output;
  21.   int topWeight, nextRemWeight;
  22.   if (currentCount >= length || remWeight == 0){
  23.    output = 1;
  24.   } else{
  25.    topWeight = myBag[currentCount];
  26.    if (topWeight > remWeight){
  27.     output = solve(remWeight, currentCount + 1);
  28.    } else {
  29.     nextRemWeight = remWeight - topWeight;
  30.     output = solve(remWeight, currentCount + 1) + solve(nextRemWeight, currentCount + 1);
  31.    }
  32.   }
  33.   return output;
  34.  }
  35. }
  36. class Knapsack {
  37.  public static void main(String[] args) {
  38.   // declare the necessary variables
  39.   int numberOfItems, capacity, itemWeight;
  40.   int[] myBag;
  41.   Result myResult;
  42.   // declare a Scanner object to read input
  43.   Scanner myScanner = new Scanner(System.in);
  44.   // read input and process them accordingly
  45.   numberOfItems = myScanner.nextInt();
  46.   myBag = new int[numberOfItems];
  47.   capacity = myScanner.nextInt();
  48.   for (int i = 0; i < numberOfItems; i++){
  49.     itemWeight = myScanner.nextInt();
  50.     myBag[i] = itemWeight;
  51.   }
  52.   myResult = new Result(myBag);
  53.   System.out.println(myResult.solve(capacity, 0));
  54.  }
  55. }
Advertisement
Add Comment
Please, Sign In to add comment