Extension 5.2: Watermelon Puzzle (5 points)

Authors

Adapted from Sit and Solve Brainteasers by Derick Niederman

Warm Up

Five watermelons, each of different weight, have been weighed in pairs to obtain the following weights:

20, 22, 23, 24, 25, 26, 27, 28, 30, 31

One way to solve this would be to figure out a mathematical algorithm for this number of watermelons and work out the weight of each watermelon. Another would be to try all of the possible combinations of weights five watermelons until you found one that has this same set of combinations of weights. Either way you did it, the specific set of watermelons that produces these weights is

[ 9, 11, 13, 14, 17 ]

Demo Video

Randomly Guessing Watermelon Weights Prohibited

Note: You must search systematically for the desired weights. Solutions that use Math.random() will recieve no credit.

Procedure

Since we have computers, and know how to write code, trying all of the possible weights of the five watermelons is now much easier. In this extension, you will take in an array of 10 weights, and you will try, iteratively, to come up with the individual weights of the five watermelons.

You should see a watermelons package in the src folder.

  1. The file you will modify for this assignment is Watermelons.java. It is already in the respository.

  2. You will complete three methods in the Watermelons class: pairCount(weights), allPairSums(weight), and findWeightsOf5Watermelons(pairSums). You are provided with two methods: toSortedCopy(array) and equalsIgnoringOrder(array) which uses toSortedCopy.

  3. Complete pairCount(int[] array).

  4. Run WatermelonsTestSuite until you have passed all of the PairCountTestSuite portion.

  5. Complete allPairSums(int[] weights)

    Given the input array weights, this method computes the pairwise-sum of each distinct

pair of index values for that array. For example, given the input {40, 20, 10, 30}, the method must compute the sums of indices (0,1), (0,2), (0,3), (1,2), (1,3), (2,3), returning the array {60, 50, 70, 30, 50, 40}

How might the method pairCount(array) be useful here?

Note: The ordering of the elements in the returned array does not matter.

  1. Run WatermelonsTestSuite until you have passed all of the AllPairSumsTestSuite portion.

  2. Investigate toSortedCopy(array) and equalsIgnoringOrder(a,b)

    How might these methods be useful to you?

  3. Complete int[] findWeightsOf5Watermelons(int[] pairSums)

    This method returns a solution to the puzzle for the array of 10 integers that are passed into it. The ordering of elements in the array you produce does not matter, as far as the provided unit test is concerned.

  4. Run WatermelonsTestSuite until you have passed all of the tests.

Testing

To run the suite of unit tests, right (control) click on WatermelonsTestSuite and choose Run as... then JUnit Test.

You have attempted of activities on this page