Here is the code following the logic from the previous post:
java 代码
The generateSumArrays() does the forward sum-ups, e.g., (1), (2), ..., this is the main functionality. There is also a floors field that holds the results from backward sum-ups, (A), (B), .... However, this field is not really used in computation, because the
starting point is dynamic, not fixed like in this field. So this is merely for information and debug. A similar method to
compute this backward sum is in another class.
Another functionality of this class is to answer the questions posted in the above Chinese paragraph. For a given height of the build, i.e., the number of floors is fixed, how many balls are optimal, e.g., if we are given a building with 10 floors, 50 balls won't reduce the minimal trials, in fact maybe it takes the same number of trials as 10 balls. These are in the first 3 methods. The basic logic is that since the worst case trials are evenly distributed, we just find one worst path of floors to count the trials.
The test cases is
java 代码
- package glassball;
-
- import junit.framework.TestCase;
-
-
-
-
- public class GlassBallPuzzleTest extends TestCase
- {
- public void test2Balls()
- {
- GlassBallPuzzle puzzle = new GlassBallPuzzle(2, 100);
- puzzle.printAllResults();
- System.out.println("minimal trials=" + puzzle.getMinimalTrials());
- assertTrue(puzzle.getMinimalTrials() == 14);
- }
-
- public void test3Balls()
- {
- GlassBallPuzzle puzzle = new GlassBallPuzzle(3, 100);
- puzzle.printAllResults();
- System.out.println("minimal trials=" + puzzle.getMinimalTrials());
- assertTrue(puzzle.getMinimalTrials() == 9);
- }
-
- public void test4Balls()
- {
- GlassBallPuzzle puzzle = new GlassBallPuzzle(4, 100);
- puzzle.printAllResults();
- System.out.println("minimal trials=" + puzzle.getMinimalTrials());
- assertTrue(puzzle.getMinimalTrials() == 8);
- int[] optimals = puzzle.getOptimalTrialsAndBalls();
- System.out.println("optimal trials and balls=" + optimals[0] + ", " + optimals[1]);
- }
-
- public void test5Balls()
- {
- GlassBallPuzzle puzzle = new GlassBallPuzzle(5, 100);
- puzzle.printAllResults();
- System.out.println("minimal trials=" + puzzle.getMinimalTrials());
- assertTrue(puzzle.getMinimalTrials() == 8);
- }
-
- public void test6Balls()
- {
- GlassBallPuzzle puzzle = new GlassBallPuzzle(6, 100);
- puzzle.printAllResults();
- System.out.println("minimal trials=" + puzzle.getMinimalTrials());
- assertTrue(puzzle.getMinimalTrials() == 8);
- }
-
- public void test50Balls()
- {
- GlassBallPuzzle puzzle = new GlassBallPuzzle(50, 200);
- puzzle.printAllResults();
- System.out.println("minimal trials=" + puzzle.getMinimalTrials());
- assertTrue(puzzle.getMinimalTrials() == 20);
- }
- }
The method test4Balls() prints out the optimal number which are verified by test5Balls() and test6Balls().