|
| 1 | +import java.util.ArrayList; |
| 2 | +import java.util.List; |
| 3 | +import java.util.Scanner; |
| 4 | + |
| 5 | +/** |
| 6 | + * User: ning wei |
| 7 | + * Date: 5/2/12 |
| 8 | + * Time: 8:23 PM |
| 9 | + * |
| 10 | + * You'll be given a list of activities and their caloric impact. |
| 11 | + * Write a program that outputs the names of activities a Dropboxer should choose to partake in |
| 12 | + * so that the sum of their caloric impact is zero. |
| 13 | + * Once an activity is selected, it cannot be chosen again. |
| 14 | + * |
| 15 | + * It is a question to find a sum to zero from all possible elements of an array |
| 16 | + * Basically use gray code to pick element from a given array and calculate the sum |
| 17 | + * |
| 18 | + */ |
| 19 | + |
| 20 | +public class ActivityZero { |
| 21 | + private String activity; |
| 22 | + private int calorie; |
| 23 | + |
| 24 | + public ActivityZero(String a, int c) { |
| 25 | + this.activity = a; |
| 26 | + this.calorie = c; |
| 27 | + } |
| 28 | + |
| 29 | + public static void main(String args[]) { |
| 30 | + |
| 31 | + List<ActivityZero> listActivityZero = new ArrayList<ActivityZero>(); |
| 32 | + |
| 33 | + Scanner scanner = new Scanner(System.in); |
| 34 | + |
| 35 | + //TODO: input exception is not handled. |
| 36 | + |
| 37 | + int n = Integer.parseInt(scanner.nextLine()); |
| 38 | + while (n > 0) { |
| 39 | + String newInput = scanner.nextLine(); |
| 40 | + String[] tempArray = newInput.split(" "); |
| 41 | + |
| 42 | + ActivityZero az = new ActivityZero(tempArray[0], Integer.parseInt(tempArray[1])); |
| 43 | + listActivityZero.add(az); |
| 44 | + |
| 45 | + n--; |
| 46 | + |
| 47 | + } |
| 48 | + |
| 49 | + scanner.close(); |
| 50 | + |
| 51 | + List<ActivityZero> tmpList = new ArrayList<ActivityZero>(); |
| 52 | + sumCalorie(listActivityZero, listActivityZero.size(), tmpList, true); |
| 53 | + |
| 54 | + } |
| 55 | + |
| 56 | + public static void sumCalorie(List<ActivityZero> list, int n, List<ActivityZero> tmpList, boolean pick) { |
| 57 | + if (n == 0) |
| 58 | + return; // start recursion back |
| 59 | + sumCalorie(list, n - 1, tmpList, true); |
| 60 | + if (pick) { |
| 61 | + tmpList.add(list.get(n - 1)); |
| 62 | + showSum(tmpList); |
| 63 | + } else { |
| 64 | + tmpList.remove(list.get(n - 1)); |
| 65 | + showSum(tmpList); |
| 66 | + } |
| 67 | + sumCalorie(list, n - 1, tmpList, false); |
| 68 | + |
| 69 | + } |
| 70 | + |
| 71 | + public static void showSum(List<ActivityZero> l) { |
| 72 | + int sumCalorie = 0; |
| 73 | + for (ActivityZero az : l) { |
| 74 | + sumCalorie += az.calorie; |
| 75 | + |
| 76 | + } |
| 77 | + if (l.size() != 0 && sumCalorie == 0) { |
| 78 | + System.out.println("The winner picks: "); |
| 79 | + for (ActivityZero az : l) { |
| 80 | + System.out.println(az.activity + " " + az.calorie); |
| 81 | + } |
| 82 | + } |
| 83 | + } |
| 84 | + |
| 85 | + |
| 86 | +} |
0 commit comments