12. Book Exercises
Chapter 12, exercises 23, 24, and 25. Write tests to prove that your work is correct. Those exercises, restated here, are:
Exercise 23: Rotate
public static int[] rotateLeft(int[] a)
: Rotate{0,1,2,3}
to{1,2,3,0}
.public static int[] rotateRight(int[] a)
: Rotate{0,1,2,3}
to{3,0,1,2}
.public static int[] rotate(int[] a, int amount)
: Rotate byamount
to the right, so to the left when amount is negative.
Exercise 24: Add Digits
-
Add two positive numbers given by arrays representing the individual digits.
public static int[] add(int[] a, int[] b)
Example 923+94=1017:
@Test public void test_add_1() { int[] a = {9,2,3}; int[] b = {9,4}; int[] ans = {1,0,1,7}; assertArrayEquals(ans, add(a,b)); }
Exercise 25: Average Two Largest
-
Find the average of the greatest two elements in an array.
public static double largestAverage(int [] data)
@Test public void test_largest_average() { int[] data = {100,40,90,30}; assertEquals(95, largestAverage(data), 0.1); int[] fdata = {-1000,-30,-31,-80}; assertEquals(-30.5, largestAverage(fdata), 0.1); int[] gdata = {100,100,50,40}; assertEquals(100, largestAverage(gdata), 0.1); }