Question

In this lab, you get to try your hand with some recursion operating on arrays and...

In this lab, you get to try your hand with some recursion operating on arrays and subarrays. All of the following methods of the class RecursionProblems must be fully recursive, with no loops allowed at all! (If-else statements are okay.) Because these methods are quite short, this last time there are six methods to write instead of the usual four. (The scoring rule is that you start gaining any points for this lab only at the third method that passes the tester.)

1.boolean allEqual(int[] arr, int start, int end) that checks if all elements in the subarray of arr from start to end, inclusive, are equal. Note that for the base case, all elements of an empty (that is, where start > end) or one-element subarray are equal by definition. After all, a subarray must by definition have at least two elements for it to have two different elements! (This principle generalizes to the counterintuitive but nonetheless true observation that any universal claim that you make about the members of an empty array is trivially true by definition.)

2.void arraycopy(double[] src, int start, double[] tgt, int start2, int len) that copies len elements from the location start of array src to the location start2 of array tgt. In other words, this method works exactly the same way as the method System.arraycopy. (But of course you are not allowed to call this existing method.) Hint: when len is less than one, do nothing. Otherwise copy the first element, and then recursively copy the remaining len - 1 elements.

3.boolean linearSearch(int[] arr, int x, int start, int end) that checks if the unsorted array arr contains the element x anywhere in the subarray from start and end, inclusive.

4.void reverse(int[] arr, int start, int end) that reverses the order of the elements in the subarray of arr from index start to end, inclusive. Note that this method does not create and return a new array, but modifies the contents of the parameter array arr in place by reassigning its elements.

5.public void parityPartition(int[] arr, int start, int end) that modifies the subarray of arr from start to end, inclusive, in place so that all odd numbers are first together in one bunch, followed by all even numbers in another bunch. The odd elements can end up in any order you want inside the first bunch, as do the even elements. For example, if your array a is currently [2, -1, 3, 4, 8, 5, -7], after the call parityPartition(a, 0, 6), the contents of this array might become [3, -1, -7, 5, 8, 4, 2]. (Hint: after testing for the base case of subarray that has only zero or one elements, the parities of the first and the last element of the subarray, whichever way they might be, will somehow allow you to continue the recursion with a smaller subarray.)

6.int countRuns(int[] arr, int start, int end) that counts how many runs (blocks of equal consecutive elements) there are in the subarray of arr from index start to index end, inclusive. For example, the array [4, 4, 4, -2, 0, -8, -8, 3, 3] has five runs, whereas the array [5, 5, 5, 5] has only one run. An empty subarray (that is, when start > end) has zero runs. (Hint: count how many elements are different from the next element.)

0 0
Add a comment Improve this question Transcribed image text
Answer #1

public class RecursionProblems {

   /**
   * Checks if all elements in the subarray of arr from start to end,
   * inclusive, are equal. Note that for the base case, all elements of an
   * empty (that is, where start > end) or one-element subarray are equal by
   * definition.
   *
   * @param arr
   *            - array
   * @param start
   *            - start index
   * @param end
   *            - end index
   */
   boolean allEqual(int[] arr, int start, int end) {
       // Check if array is empty
       if (start > end)
           return true;

       return (arr[start] == arr[end]) && allEqual(arr, start, end - 1);
   }

   /**
   * Copies len elements from the location start of array src to the location
   * start2 of array tgt. In other words, this method works exactly the same
   * way as the method System.arraycopy. (But of course you are not allowed to
   * call this existing method.) Hint: when len is less than one, do nothing.
   * Otherwise copy the first element, and then recursively copy the remaining
   * len - 1 elements.
   *
   * @param src
   *            - source array
   * @param start
   *            - start index in source array
   * @param tgt
   *            - target array
   * @param start2
   *            - start index of target array
   * @param len
   *            - number of elements to copy from source array
   */
   void arraycopy(double[] src, int start, double[] tgt, int start2, int len) {
       if (len < 1)
           return;

       // Copy element from source to target
       tgt[start2] = src[start];
       arraycopy(src, start + 1, tgt, start2 + 1, len - 1);
   }

   /**
   * Checks if the unsorted array arr contains the element x anywhere in the
   * subarray from start and end, inclusive.
   *
   * @param arr
   *            - array
   * @param x
   *            - search element
   * @param start
   *            - start index
   * @param end
   *            - end index
   */
   boolean linearSearch(int[] arr, int x, int start, int end) {
       if (start > end)
           return false;

       return ((arr[start] == x) || (arr[end] == x)) || linearSearch(arr, x, start + 1, end - 1);
   }

   /**
   * Reverses the order of the elements in the subarray of arr from index
   * start to end, inclusive. Note that this method does not create and return
   * a new array, but modifies the contents of the parameter array arr in
   * place by reassigning its elements.
   *
   * @param arr
   *            - Array
   * @param start
   *            - start index
   * @param end
   *            - end index
   */
   void reverse(int[] arr, int start, int end) {
       if (start > end)
           return;

       // Swap elements at start and end
       int temp = arr[start];
       arr[start] = arr[end];
       arr[end] = temp;
       reverse(arr, start + 1, end - 1);
   }

   /**
   * Shifts array elements one position down
   *
   * @param arr
   *            - Array
   * @param index
   *            - index
   */
   private void downShiftArray(int[] arr, int index) {
       if (index < 1)
           return;

       // Shift element
       arr[index] = arr[index - 1];
       downShiftArray(arr, index - 1);
   }

   /**
   * Modifies the subarray of arr from start to end, inclusive, in place so
   * that all odd numbers are first together in one bunch, followed by all
   * even numbers in another bunch. The odd elements can end up in any order
   * you want inside the first bunch, as do the even elements. For example, if
   * your array a is currently [2, -1, 3, 4, 8, 5, -7], after the call
   * parityPartition(a, 0, 6), the contents of this array might become [3, -1,
   * -7, 5, 8, 4, 2]. (Hint: after testing for the base case of subarray that
   * has only zero or one elements, the parities of the first and the last
   * element of the subarray, whichever way they might be, will somehow allow
   * you to continue the recursion with a smaller subarray.)
   *
   * @param arr
   *            - Array
   * @param start
   *            - start index
   * @param end
   *            - end index
   */
   public void parityPartition(int[] arr, int start, int end) {
       if (start > end)
           return;

       // Check if element at start and end is odd
       if ((arr[start] % 2) != 0) {
           int oddNum = arr[start];
           downShiftArray(arr, start);
           arr[0] = oddNum;
       }

       if ((arr[end] % 2) != 0)
           parityPartition(arr, start + 1, end);
       else
           parityPartition(arr, start + 1, end - 1);
   }

   /**
   * Counts how many runs (blocks of equal consecutive elements) there are in
   * the subarray of arr from index start to index end, inclusive. For
   * example, the array [4, 4, 4, -2, 0, -8, -8, 3, 3] has five runs, whereas
   * the array [5, 5, 5, 5] has only one run. An empty subarray (that is, when
   * start > end) has zero runs. (Hint: count how many elements are different
   * from the next element.)
   *
   * @param arr
   *            - Array
   * @param start
   *            - start index
   * @param end
   *            - end index
   */
   int countRuns(int[] arr, int start, int end) {
       if (start >= end)
           return 0;
      
       int count = 0;
       if (start == 0)
           count = 1;
          
       // Check if the next element is different
       if (arr[start] != arr[start + 1])
           count = 1;
      
       return count + countRuns(arr, start + 1, end);
   }

   /**
   * Displays the array
   */
   public static void printArray(int[] arr) {
       System.out.print("Array: ");
       if (arr.length >= 1) {
           System.out.print(arr[0]);

           for (int i = 1; i < arr.length; i++)
               System.out.print(", " + arr[i]);
       }
       System.out.println();
   }

   /**
   * Displays the array
   */
   public static void printArray(double[] arr) {
       System.out.print("Array: ");
       if (arr.length >= 1) {
           System.out.print(arr[0]);

           for (int i = 1; i < arr.length; i++)
               System.out.print(", " + arr[i]);
       }
       System.out.println();
   }

   public static void main(String[] args) {
       RecursionProblems r = new RecursionProblems();

       System.out.println("------------------------TEST allEqual------------------------");
       int[] emptyArr = {};
       printArray(emptyArr);
       System.out.println("allEqual: " + r.allEqual(emptyArr, 0, emptyArr.length - 1) + "\n");

       int[] oneEltArr = { 1 };
       printArray(oneEltArr);
       System.out.println("allEqual: " + r.allEqual(oneEltArr, 0, oneEltArr.length - 1) + "\n");

       int[] equalArr = { 1, 1, 1, 1, 1 };
       printArray(equalArr);
       System.out.println("allEqual: " + r.allEqual(equalArr, 0, equalArr.length - 1) + "\n");

       int[] unEqualArr = { 1, 1, 2, 1, 1 };
       printArray(unEqualArr);
       System.out.println("allEqual: " + r.allEqual(unEqualArr, 0, unEqualArr.length - 1) + "\n");

       System.out.println("------------------------TEST arraycopy------------------------");
       double[] source = { 1, 2, 3, 4, 5 };
       double[] target = { 11, 12, 13, 14, 15 };
       r.arraycopy(source, 1, target, 2, 3);
       System.out.print("Source ");
       printArray(source);
       System.out.print("Target ");
       printArray(target);
       System.out.println();

       System.out.println("------------------------TEST linearSearch------------------------");
       int[] array = { 23, 18, 45, 90, 12, 3 };
       int searchElt = 12;
       printArray(array);
       System.out.println(searchElt + " found: " + r.linearSearch(array, searchElt, 0, array.length - 1) + "\n");

       System.out.println("------------------------TEST reverse------------------------");
       printArray(array);
       r.reverse(array, 0, array.length - 1);
       System.out.print("Reverse ");
       printArray(array);
       System.out.println();

       System.out.println("------------------------TEST parityPartition------------------------");
       printArray(array);
       r.parityPartition(array, 0, array.length - 1);
       System.out.println("After parityPartition");
       printArray(array);
       System.out.println();

       int[] array2 = { 2, -1, 3, 4, 8, 5, -7 };
       printArray(array2);
       r.parityPartition(array2, 0, array2.length - 1);
       System.out.println("After parityPartition");
       printArray(array2);
       System.out.println();

       System.out.println("------------------------TEST countRuns------------------------");
       int[] array3 = {4, 4, 4, -2, 0, -8, -8, 3, 3};
       printArray(array3);
       System.out.println("Number of runs: " + r.countRuns(array3, 0, array3.length - 1) + "\n");
      
       printArray(equalArr);
       System.out.println("Number of runs: " + r.countRuns(equalArr, 0, equalArr.length - 1) + "\n");
      
       printArray(emptyArr);
       System.out.println("Number of runs: " + r.countRuns(emptyArr, 0, emptyArr.length - 1) + "\n");
   }
}


SAMPLE OUTPUT:

Array: allEqual: true Array: 1 allEqual: true allEqual: true Array: 1, 1, 2, 1, 1 allEqual: false --TEST arraycopy- Source Ar

Add a comment
Know the answer?
Add Answer to:
In this lab, you get to try your hand with some recursion operating on arrays and...
Your Answer:

Post as a guest

Your Name:

What's your source?

Earn Coins

Coins can be redeemed for fabulous gifts.

Not the answer you're looking for? Ask your own homework help question. Our experts will answer your question WITHIN MINUTES for Free.
Similar Homework Help Questions
  • Consider a non-empty int array ints. A contiguous subarray ints[ start .. start + len -1...

    Consider a non-empty int array ints. A contiguous subarray ints[ start .. start + len -1 ] (with starting index start and length len) is called a flat if all elements of that subarray are equal. Furthermore, such a subarray is called a plateau if it is flat and each of the elements ints[start -1] and ints[start + len] that immediately proceed/succeed the subarray are either nonexistent (i.e., out of array’s index range) or are strictly smaller than the elements...

  • JAVA Objectives: 1. Apply linear search algorithm 2. Apply select sort algorithm 3. Apply array iteration...

    JAVA Objectives: 1. Apply linear search algorithm 2. Apply select sort algorithm 3. Apply array iteration skill Problem description: Write the following eight methods and write a main function to test these methods // return the index of the first occurrence of key in arr // if key is not found in arra, return -1 public static int linearSearch(int arr[], int key) // sort the arr from least to largest by using select sort algorithm public stati void selectSort(int arr[])...

  • Programming Assignment #7 (Recursion) This assignment is to write some methods that perform simple array operations...

    Programming Assignment #7 (Recursion) This assignment is to write some methods that perform simple array operations recursively. Specifically, you will write the bodies for the recursive methods of the ArrayRecursion class, available on the class web page. No credit will be given if any changes are made to ArrayRecursion.java, other than completing the method bodies Note that the public methods of ArrayRecursion – contains(), getIndexOfSmallest(), and sort() – cannot be recursive because they have no parameters. Each of these methods...

  • Develop a Generic String List (GSL). NOTE: I have done this lab but someting is wrong...

    Develop a Generic String List (GSL). NOTE: I have done this lab but someting is wrong here is what i was told that was needed. Ill provide my code at the very end. Here is what is missing : Here is my code: public class GSL { private String arr[]; private int size; public GSL() {     arr = new String[10];     size = 0; } public int size() {     return size; } public void add(String value) {    ...

  • 5. (40 Points) Write a complete Java class named ArrayMethods that implements the methods listed below....

    5. (40 Points) Write a complete Java class named ArrayMethods that implements the methods listed below. All the methods accept the following parameters: Parameters: intar An array of int values. int firstIndex The index of the first element to include in the sum. int lastIndex The index of the last element to include in the sum. Please note that all methods must verify the validity of first Index and lastIndex. public static int sum(int[] arr, int first Index, int lastIndex)...

  • must provide the following public interface: public static void insertSort(int [] arr); public static void selectSort(int...

    must provide the following public interface: public static void insertSort(int [] arr); public static void selectSort(int [] arr); public static void quickSort(int [] arr); public static void mergeSort(int [] arr); The quick sort and merge sort must be implemented by using recursive thinking. So the students may provide the following private static methods: //merge method //merge two sorted portions of given array arr, namely, from start to middle //and from middle + 1 to end into one sorted portion, namely,...

  • c++ please read all question edit the program to test different random sizes of the array and give me the time in a file will be like random size of the array and next to it the time it took for each...

    c++ please read all question edit the program to test different random sizes of the array and give me the time in a file will be like random size of the array and next to it the time it took for each size Im trying to do time analysis for Quick sort but i keep getting time = 0 also i want edit the program to test different random sizes of the array and give me the time in a...

  • I currently have this but it doesn't work for the three item arrays public class Quicksort...

    I currently have this but it doesn't work for the three item arrays public class Quicksort extends Partitioner { public static void quicksort(int[] values) { if (values == null || values.length < 2) { return; } quicksort(values, 0, values.length - 1); } private static void quicksort(int[] values, int start, int end) { System.out.println(values); System.out.println(start); System.out.println(end); if (values == null || Math.abs(start - end) == 1) { return; } if (end > start) { int pivotValueIndex = partition(values, start, end); quicksort(values,...

  • Write an application with two classes USING JAVA METHODS HAVE TO BE CREATED USING RECURSION. First...

    Write an application with two classes USING JAVA METHODS HAVE TO BE CREATED USING RECURSION. First class named Recursion has the following three recursive methods: // PRECONDITION n is positive integer. Method sumTerms returns sum of terms that are // reciprocal values of first n integers, with  alternating signs.      // For example,  sumTerms(7) returns  the following:  1/1 – 1/2  + 1/3 – 1/4  + 1/5 -1/6 + 1/7. // Terms with an odd denominator have positive sign, and terms with even denominator have // negative sign.  ...

  • Arrays in Functions 2. Arrays in Functions You can use both the array index variables and...

    Arrays in Functions 2. Arrays in Functions You can use both the array index variables and the entire array itself as arguments to functions. The following program updates the elements of the array grades, one-by-one. Thus, we have used a call-by-reference-ish mechanism to update the values (although no & was used). Note that there is a major difference between the grade in the function call and the one in the function definition. In the statement get_grade (grades[i]); "grades" is the...

ADVERTISEMENT
Free Homework Help App
Download From Google Play
Scan Your Homework
to Get Instant Free Answers
Need Online Homework Help?
Ask a Question
Get Answers For Free
Most questions answered within 3 hours.
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT