Question

In: Computer Science

I'm working with using recursion to find the sum and the min of these two arrays...

I'm working with using recursion to find the sum and the min of these two arrays respectively. So far what I have gives the correct answers when they run, however when I use a test code on them they fail because they cannot handle out of bounds points, for example if int[] sumMe = { } or if the position is set to the last number "89" in the array. I kinda know what I'm supposed to tell it but not how to properly implement it, if you could help be adjust the code to catch these out of bounds instances I'd very much appreciate it.
I'll put the failed messages for each of these under the test code I put down in case it helps.


public class test {
    public static void main(String[] args) {
        int[] sumMe = { 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89 };
        System.out.printf("Array Sum: %d\n", arraySum(sumMe, 0));


        int[] minMe = { 0, 1, 1, 2, 3, 5, 8, -42, 13, 21, 34, 55, 89 };
        System.out.printf("Array Min: %d\n", arrayMin(minMe, 0));
    }
    public static long arraySum(int[] data, int position) {
        if (position <= data.length && position >= 0) {
            if (data.length - 1 == position) {
                return data[position];
            }
            else {
                return data[position] + arraySum(data, position + 1);
            }
        }
        return 0;
    }

    public static int arrayMin(int[] data, int position) {
        int min;
        int i;
        min = data[position];
        for (i = 0; i < data.length; i++) {
            if (min > data[i]) {
                min = data[i];
                arrayMin(data, i++);
            }
        }
        return min;
    }
}

Failed test in arrayMin:

java.lang.AssertionError: ArrayMin must be able to handle position of
Expected :89
Actual :1

Failed test in arraySum:

java.lang.ArrayIndexOutOfBoundsException: Index 0 out of bounds for length 0

Solutions

Expert Solution

/***************************Recursion.java***************/

import org.junit.Assert;

public class RecursionTest {
   @org.junit.Test
   public void RecursionTestArraySumInputTest() {
       int[] emptyArray = {};

      
       Assert.assertEquals("ArraySum must be able to handle an empty array", 0, Recursion.arraySum(emptyArray, 0));
       Assert.assertEquals("ArraySum must be able to handle bad position values", 0,
               Recursion.arraySum(emptyArray, 1));
   }

   @org.junit.Test
   public void RecursionTestArraySumTest() {
       int[] array = { 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89 };
       int position = 4;

       Assert.assertEquals("ArraySum calculated an incorrect sum", 232, Recursion.arraySum(array, 0));
       Assert.assertEquals(
               String.format("ArraySum calculated an incorrect sum when starting at position %d", position), 225,
               Recursion.arraySum(array, position));

       position = array.length - 1;
       Assert.assertEquals(String
               .format("ArraySum calculated an incorrect sum when starting at position %d (end of array)", position),
               89, Recursion.arraySum(array, position));
   }

   @org.junit.Test
   public void RecursionTestArrayMinTest() {
       int[] inOrder = { 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89 };
       int[] reverseOrder = { 10, 9, 8, 7, 6, 5, 4, 3, 2, 1 };
       int[] randomOrder = { 5, 1, 100, 7, 6, 2, 0 };
       int[] randomWithNeg = { 5, 1, 100, -6, 7, 6, 2, 0, -1 };

       Assert.assertEquals("ArrayMin must be able to find the correct min with an in-order array", 1,
               Recursion.arrayMin(inOrder, 0));
       Assert.assertEquals("ArrayMin must be able to find the correct min with a reverse-ordered array", 1,
               Recursion.arrayMin(reverseOrder, 0));
       Assert.assertEquals("ArrayMin must be able to find the correct min with a random-ordered array", 0,
               Recursion.arrayMin(randomOrder, 0));
       Assert.assertEquals("ArrayMin must be able to find the correct min with a random-ordered array with negatives",
               -6, Recursion.arrayMin(randomWithNeg, 0));
   }

   @org.junit.Test
   public void RecursionTestArrayMinInputTest() {
       int[] inOrder = { 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89 };
       int position = inOrder.length - 1;

       Assert.assertEquals(String.format("ArrayMin must be able to handle position of ", position), 89,
               Recursion.arrayMin(inOrder, position));
   }

   @org.junit.Test
   public void RecursionTestIsWordSymmetricInputTest() {
       String[] emptyArray = {};
       String[] array = { "I" };
       String[] array2 = "I have to push the pram a lot!".split(" ");

       Assert.assertEquals("IsWordSymmetric must be able to handle an empty array", true,
               Recursion.isWordSymmetric(emptyArray, 0, 0));
       Assert.assertEquals("IsWordSymmetric must be able to handle a single word", true,
               Recursion.isWordSymmetric(array, 0, 0));
       Assert.assertEquals("IsWordSymmetric must be able to handle a start and end position at the end of the array",
               false, Recursion.isWordSymmetric(array2, array2.length - 2, array2.length - 1));
       Assert.assertEquals("IsWordSymmetric must be able to handle a start and end position at the end of the array",
               true, Recursion.isWordSymmetric(array2, array2.length - 1, array2.length - 1));
   }

   @org.junit.Test
   public void RecursionTestIsWordSymmetricTest() {
       String[] array = "I have to push the pram a lot!".split(" ");
       String[] array1 = "this easy this".split(" ");
       String[] array2 = "You can cage a swallow can't you but you can't swallow a cage can you".split(" ");

       Assert.assertEquals(false, Recursion.isWordSymmetric(array, 0, array.length - 1));
       Assert.assertEquals(true, Recursion.isWordSymmetric(array1, 0, array1.length - 1));
       Assert.assertEquals("IsWordSymmetric must be case insensitive", true,
               Recursion.isWordSymmetric(array2, 0, array2.length - 1));
   }

   @org.junit.Test
   public void RecursionTestComputePyramidWeightsInputTest() {
       double[][] weights = { {} };
       double[][] weights1 = { { 51.18 }, { 55.90, 131.25 }, { 69.05, 133.66, 132.82 },
               { 53.43, 139.61, 134.06, 121.63 } };

       Assert.assertEquals("ComputePyramidWeights must be able to handle an empty array", 0.0,
               Recursion.computePyramidWeights(weights, 0, 0), 0.001);
       Assert.assertEquals("ComputePyramidWeights must be able to handle negative row values", 0.0,
               Recursion.computePyramidWeights(weights, -1, 0), 0.001);
       Assert.assertEquals("ComputePyramidWeights must be able to handle negative col values", 0.0,
               Recursion.computePyramidWeights(weights, 0, -1), 0.001);
       Assert.assertEquals("ComputePyramidWeights must be able to handle invalid column", 0.0,
               Recursion.computePyramidWeights(weights1, 0, 3), 0.001);
       Assert.assertEquals("ComputePyramidWeights must be able to handle invalid row", 0.0,
               Recursion.computePyramidWeights(weights1, 4, 0), 0.001);
   }

   @org.junit.Test
   public void RecursionTestComputePyramidWeightsTest() {
       double weights[][] = { { 51.18 }, { 55.90, 131.25 }, { 69.05, 133.66, 132.82 },
               { 53.43, 139.61, 134.06, 121.63 } };

       Assert.assertEquals("ComputePyramidWeights must be able to handle an array with a single row and col", 51.18,
               Recursion.computePyramidWeights(weights, 0, 0), 0.001);
       Assert.assertEquals("ComputePyramidWeights must be able to handle an array with multiple rows and one col",
               108.327, Recursion.computePyramidWeights(weights, 3, 0), 0.001);
       Assert.assertEquals("ComputePyramidWeights must be able to handle an array with multiple cols and rows", 227.25,
               Recursion.computePyramidWeights(weights, 3, 3), 0.001);
   }

   @org.junit.Test
   public void RecursionTestHowManyOrganismsInputTest() {
       char[][] image = { {} };
       char[][] image1 = { { '*' } };
       char[][] image2 = { { '*', ' ' } };
       char[][] image3 = { { '*', ' ' }, { '*' }, { '*', '*', '*' } };

       Assert.assertEquals("HowManyOrganisms must be able to handle an empty image", 0,
               Recursion.howManyOrganisms(image));
       Assert.assertEquals("HowManyOrganisms must be able to handle an image with a single row/col", 1,
               Recursion.howManyOrganisms(image1));
       Assert.assertEquals("HowManyOrganisms must be able to handle a rectangular image", 1,
               Recursion.howManyOrganisms(image2));
       Assert.assertEquals("HowManyOrganisms must be able to handle a ragged image", 1,
               Recursion.howManyOrganisms(image3));
   }

   @org.junit.Test
   public void RecursionTestHowManyOrganismsTest() {
       char[][] image = { { '*', ' ', ' ', '*', ' ', ' ', ' ', ' ', '*', ' ' },
               { ' ', '*', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ' },
               { ' ', ' ', ' ', ' ', ' ', ' ', '*', ' ', ' ', ' ' },
               { ' ', '*', ' ', '*', ' ', '*', ' ', ' ', ' ', ' ' },
               { ' ', ' ', ' ', ' ', '*', ' ', '*', ' ', '*', ' ' },
               { ' ', '*', ' ', ' ', ' ', '*', ' ', '*', ' ', '*' },
               { ' ', ' ', ' ', '*', ' ', ' ', ' ', ' ', '*', ' ' },
               { ' ', ' ', '*', ' ', ' ', ' ', ' ', ' ', ' ', ' ' },
               { ' ', ' ', ' ', ' ', '*', ' ', ' ', ' ', '*', ' ' },
               { ' ', ' ', ' ', ' ', ' ', '*', ' ', ' ', ' ', ' ' } };

       char[][] image1 = { { '*', '*', ' ', '*', '*', '*', '*', '*', '*', '*' },
               { '*', '*', ' ', ' ', '*', ' ', ' ', ' ', '*', '*' },
               { '*', ' ', ' ', ' ', '*', ' ', '*', '*', ' ', '*' },
               { '*', '*', ' ', '*', '*', '*', '*', ' ', ' ', '*' },
               { '*', '*', '*', ' ', '*', ' ', '*', ' ', '*', '*' },
               { '*', '*', '*', ' ', '*', '*', '*', '*', '*', '*' },
               { '*', ' ', ' ', '*', ' ', ' ', ' ', ' ', '*', '*' },
               { '*', ' ', '*', '*', ' ', ' ', ' ', ' ', '*', '*' },
               { '*', ' ', '*', '*', '*', '*', ' ', ' ', '*', '*' },
               { '*', '*', '*', '*', '*', '*', '*', '*', '*', '*' } };
       Assert.assertEquals(21, Recursion.howManyOrganisms(image));
       Assert.assertEquals("HowManyOrganisms should be able to handle cascading", 1,
               Recursion.howManyOrganisms(image1));
   }

   @org.junit.Test
   public void RecursionTestHowManyOrganismsInputRaggedTest() {
       char[][] image = { { '*', ' ' }, { ' ' }, { '*', ' ', '*' } };
       char[][] image1 = { { '*', ' ' }, { '*' }, { '*', '*', '*' } };

       Assert.assertEquals("HowManyOrganisms must be able to handle a ragged image", 3,
               Recursion.howManyOrganisms(image));
       Assert.assertEquals("HowManyOrganisms must be able to handle a ragged image with cascading", 1,
               Recursion.howManyOrganisms(image1));
   }
}

Please let me know if you have any doubt or modify the answer, Thanks :)


Related Solutions

For this question we will be using arrays and classes in Java to compute the min,...
For this question we will be using arrays and classes in Java to compute the min, max, and average value of items for a given array of integers. Complete the following using the base template provided below: -Create methods for min, max, and average and call them from main to print out their values. -Add a method to determine the median (http://www.mathsisfun.com/median.html) and print that value. This method is currently not in the template, so you will need to add...
I'm working in Java and am working on a project where I need to find an...
I'm working in Java and am working on a project where I need to find an average. The catch is that for some of the values there is no data because they will be entered at a later date. I have variables assigned so that for each entry if there is an input I'll have it say _____available = 1, otherwise the variable will equal 0. I'll use an example to make this more clear. Let's say I am trying...
In C++ write a function to find a product of two matrices using arrays. The function...
In C++ write a function to find a product of two matrices using arrays. The function should be general and should accept any size matrices.
I'm trying to get the union of two arrays and I tried making a loop that...
I'm trying to get the union of two arrays and I tried making a loop that does so. I tried also making the loop give me the size of the array as well from the union of the two arrays. Please check my loop to see what is wrong with it because it is not doing what I want it to do. I'm also not sure how to get the correct size of the array after the two arrays have...
Hello there, I'm wondering can you do this problem without arrays? Using the given code on...
Hello there, I'm wondering can you do this problem without arrays? Using the given code on C++ Platform. Let me know ASAP. #include <iostream> #include <time.h> using namespace std; void shoot(bool &targetAlive, double accuracy) { double random = (rand() % 1000) / 1000.; targetAlive = !(random < accuracy); } int startDuel(int initialTurn) { bool personAlive[3] = {true, true, true}; double accuracy[3] = {0.333, 0.5, 1.0}; int turn = initialTurn; // which person has to shoot, initialTurn represents the first person...
Objective: The goal of this lab is to practice (ragged) 2D arrays and simple recursion (in...
Objective: The goal of this lab is to practice (ragged) 2D arrays and simple recursion (in two separate parts). You are not allowed to use any of the built-in classes for this lab. If you find yourself needing to import anything at the top of your class, you are doing it wrong. Part A a) Create a class method called printArray2D that accepts a 2D integer array and prints out the values formatted such that each value occupies 4 spaces...
Hi. I'm trying to write a program that uses dynamic memory management to create two arrays....
Hi. I'm trying to write a program that uses dynamic memory management to create two arrays. splice() must create the third array and return a pointer to main(). Main() must capture the pointer returned from the splice() function. Sol'n so far, I get the results of the first and second array, but it isn't showing the results of the spliced function: #include <iostream> using namespace std; // Function int* splice() inserts the 2nd array into 1st array starting at int...
I'm working on a scatter-plot program in Python using Pandas, Matplotlib, Numpy, etc. I'm pulling data...
I'm working on a scatter-plot program in Python using Pandas, Matplotlib, Numpy, etc. I'm pulling data from a CSV file, which has no names, just numbers. All I did was to read a .csv file. How do I pull data from three columns which contains about 1500 rows with just numbers and make a scatter plot with two in the x-axis and the third in the y-axis?
a. Two dice are rolled; find the probability that the sum of the two numbers is...
a. Two dice are rolled; find the probability that the sum of the two numbers is 7. b. If one card is drawn from a standard deck, find the probability of getting a spade card or a Queen. c. A couple has 3 children, find the probability that exactly one are girls.
*****I'm using excel spreadsheet so I'm stuck on how to find a least square straight line...
*****I'm using excel spreadsheet so I'm stuck on how to find a least square straight line after linearizing the relationship. I do not have mini lab. I'm using excel.. The following are the average distances of the planets in the solar system from the sun. Planet No Planet Distance (millions of miles) 1 Pluto 47.163 2 Venus 67.235 3 Earth 92.960 4 Mars 141.61 5 Asteroids 313.00 6 Jupiter 483.60 7 Saturn 886.70 8 Uranus 1783.0 9 Neptune 2794.0 10...
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT