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

  1. public static int[] rotateLeft(int[] a): Rotate {0,1,2,3} to {1,2,3,0}.
  2. public static int[] rotateRight(int[] a): Rotate {0,1,2,3} to {3,0,1,2}.
  3. public static int[] rotate(int[] a, int amount): Rotate by amount to the right, so to the left when amount is negative.

Exercise 24: Add Digits

  1. 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

  1. 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);
    }