After class on September 3rd, a few of you asked for additional practice with basic Java programs. Here are a few suggested problems, in order of increasing difficulty. Skip ahead as far as you'd like. No starter files are provided.
For each problem:
No starter code is provided. Use examples from class and the textbook to write your solutions.
You can use whatever tool you'd like to write and run your code. This could be the in browser compiler, javac/java on your own computer or the lab machines, etc.
In case there's interest, a reddit thread for posting/discussion solutions is available at this link.
For each problem, use the main method to perform an ad-hoc test (by ad-hoc, I just mean a crude test that isn't generalizable like the fancier tests that you'll be developing in HW1).
Part 1: Max
Write a function max(int[] a) that returns the maximum value of the an int array. Try writing this function using both a while loop and a for loop. See the sidebar for convenient syntax for creating arrays.
Part 2A: 3SUM
Suppose we have an array of integers int[] a. The 3SUM problem asks if there are three integers in a[] such that their sum is zero.
For this problem, write a function threeSum(int[] a) that returns true if there exist three integers in a that sum to zero and false otherwise. Integers may be used more than once. As in part 1, use your main function to perform an ad-hoc test that threeSum works.
For loops will look a lot more compact than while loops for this problem.
Examples:
threeSum({-6, 2, 4}) is true, can select -6, 2, and 4.
threeSum({-6, 2, 5}) is false.
threeSum({-6, 3, 10, 200}) is true, can select -6, 3, and 3.
threeSum({8, 2, -1, 15}) is true, can select 2, -1, and -1.
threeSum({8, 2, -1, -1, 15}) is true, can select 2, -1, -1.
threeSum({5, 1, 0, 3, 6}) is true, can select 0, 0, and 0.
This might seem daunting at first, but it's relatively straightforward. For a hint, highlight: An alternate way of stating the problem: Do there exist three indices (not necessarily distinct) f, g, and h such that a[f] + a[g] + a[h] == 0?
Part 2B: 3SUM_DISTINCT
Repeat the exercise from Part 2B, but with the constraint that each number can be used only once.
Examples:
threeSumDistinct({-6, 2, 4}) is true, can select -6, 2, and 4.
threeSumDistinct({-6, 2, 5}) is false.
threeSumDistinct({-6, 3, 10, 200}) is false.
threeSumDistinct({8, 2, -1, 15}) is false.
threeSumDistinct({8, 2, -1, -1, 15}) is true, can select 2, -1, and -1.