Question

import java.util.Arrays; import stdlib.*; public class CSC300Homework4 {    /**    * As a model for...

import java.util.Arrays;
import stdlib.*;


public class CSC300Homework4 {

   /**
   * As a model for Problem 1, here are two functions to find the minimum value of an array of ints
   * an iterative version and a recursive version
   *
   * precondition: list is not empty
   /** iterative version */
   public static double minValueIterative (int[] list) {
       int result = list[0];
       int i = 1;
       while (i < list.length) {
           if (list[i] < result) result = list[i];
           i = i + 1;
       }
       return result;
   }

   /** recursive version
   * Find minimum of a list of size N starting at location 0
   * Smaller problem is : Find minimum of list of size N-1, starting at 0
   *
   * precondition: list is not empty
   */
   public static int minValueRecursive (int[] list) {
       return minValueHelper (list, list.length);
   }
   private static int minValueHelper (int[] list, int n) {
       if (n == 1) // the list of size 1 is the single element list[0]
           return list[0]; // the minimum of this list is just that element.

       // else: find minimum of smaller list

       int minOfSmallerList = minValueHelper( list, n-1); // recursive call, 'smaller' list

       // now compare min of smaller list to 'last' element of this list
       // the list is of size n, the 'last' element is at position n-1
       // because indexes start at 0.
       int theMin;

       if ( list[n-1] < minOfSmallerList)
           theMin = list[n-1];
       else
           theMin = minOfSmallerList;

       return theMin;
   }

   /**
   * PROBLEM 1: Translate the following summing function from iterative to
   * recursive.
   *
   * You should write a helper method. You may not use any "fields" to solve
   * this problem (a field is a variable that is declared "outside" of the
   * function declaration --- either before or after).
   *
   * Precondition: a list of ints, - maybe empty!
   * Postcondition: the sum of the positive values is returned
   */
   public static int sumOfPositives (int[] a) {
       int result = 0;
       int i = 0;
       while (i < a.length) {
           if ( a[i] > 0)
               result = result + a[i];
           i = i + 1;
       }
       return result;
   }

   public static int sumOfPositivesRecursive (int[] a) {
       return -1; // TODO 1 replace this by a call to your helper function, then write the helper function below
      
   }
// this would be a good place to put the helper function for #1
   /**
   * Here is an in-place iterative function to reverse an array.
   *
   * in-place means: we don't create an extra array (to simplify coding)
   *
   */
   public static void reverseIterative (int[] a) {
       int hi = a.length - 1;
       int lo = 0;
       while (lo < hi) {
           int loVal = a[lo];
           int hiVal = a[hi];
           a[hi] = loVal;
           a[lo] = hiVal;
           lo = lo + 1;
           hi = hi - 1;
       }
   }
/*
* * PROBLEM 2: Convert the above iterative function to a recursive version
*
   * You should write a helper method. You may not use any "fields" to solve
   * this problem (a field is a variable that is declared "outside" of the
   * function declaration --- either before or after).
   * You may not use any other methods
   *
   * Your helper function must be parameterized to allow a smaller problem to
   * be specified. How do you reverse an array of size N?
   * (the answer is NOT: reverse an array of size N-1 ! )
*/
   public static void reverseArray (int[] a) {
       return; // TODO 2 replace this by a call to your recursive helper function, then write the helper function below
      
   }
// a good place for your helper function for #2
   /**
   * PROBLEM 3: merge together two sorted arrays of ints into a new array.
   *
   * Example1 merge: [-1 3 5 7 ] with [ 2 4 6 8] would yield [-1 2 3 4 5 6 7 8]
   * Example2 merge: [1 6 ] with [ 2 3 8 9] would yield [1 2 3 6 8 9]
   * There is no guarantee about the size of either array. When/if you run out of elements in
   * either array, copy all the remaining elements from the nonempty array to the the new array
   * preconditions:
   * both arrays are sorted low to high
   * there are no duplicate values among the two arrays
   * either array may be empty
   * postcondition: return an array with all elements from both arrays sorted from low to high
   *
   * You may not use any additional methods, sorting routines etc
   * For full credit, your solution may only go through each array one time ( so in particular - no nested loops)
   *
   * You will need to create a new array inside the function
   * You do not have to write this recursively.
   */

   public static int[] mergeArrays( int[] a, int[] b) {

       int[] answer = new int[0]; // an empty array to have something to return
       return answer; // ToDo 3 . Fix this.
   }


   /*
   * exercising functions and main.
   * There are no Todo's for you in the code below.
   */
   public static void mergeArrayTests() {

       int a[] = new int[] {1,3,5,7,9,11};
       int b[] = new int[] {2,4,6};
       int[] combinedArray = mergeArrays( a,b);
       StdOut.println("merging: "+ Arrays.toString(a) + " " + Arrays.toString(b));
       StdOut.println(" --> " + Arrays.toString(combinedArray));

       int c[] = new int[] {1,3,5,7,9,11};
       int d[] = new int[] {2,4};
       combinedArray = mergeArrays( c,d);
       StdOut.println("merging: "+ Arrays.toString(c) + " " + Arrays.toString(d));
       StdOut.println(" --> " + Arrays.toString(combinedArray));

       int e[] = new int[] {1,3,5,7,9,11};
       int f[] = new int[] {};
       combinedArray = mergeArrays( e,f);
       StdOut.println("merging: "+ Arrays.toString(e) + " " + Arrays.toString(f));
       StdOut.println(" --> " + Arrays.toString(combinedArray));

       int g[] = new int[] {3,11};
       int h[] = new int[] {2,4,6,8,10};
       combinedArray = mergeArrays( g,h);
       StdOut.println("merging: "+ Arrays.toString(g) + " " + Arrays.toString(h));
       StdOut.println(" --> " + Arrays.toString(combinedArray));
   }

   public static void main (String[] args) {

       StdOut.println(" This main function calls your functions for a variety of inputs");
       StdOut.println(" and simply prints the results");
       StdOut.println(" It does NOT check to see if your functions return the correct values");
       StdOut.println(" It is up to you to review the output and verify the results");
       StdOut.println("***************************************************************");
       int[] list0 = new int[] {};
       int[] list1 = new int[] { 5 };
       int[] list2 = new int[] { 3, 4 };
       int[] list3 = new int[] { -2, 3, -4 };
       int[] list4 = new int[] { -1, -2, -4, -5 };
       int[] list5 = new int[] { 6, 1, 2, -3, 8 };

       StdOut.format(" list: %s sum of positives: %d\n",Arrays.toString(list0), sumOfPositivesRecursive (list0));
       StdOut.format(" list: %s sum of positives: %d\n",Arrays.toString(list1), sumOfPositivesRecursive (list1));
       StdOut.format(" list: %s sum of positives: %d\n",Arrays.toString(list2), sumOfPositivesRecursive (list2));
       StdOut.format(" list: %s sum of positives: %d\n",Arrays.toString(list3), sumOfPositivesRecursive (list3));
       StdOut.format(" list: %s sum of positives: %d\n",Arrays.toString(list4), sumOfPositivesRecursive (list4));
       StdOut.format(" list: %s sum of positives: %d\n",Arrays.toString(list5), sumOfPositivesRecursive (list5));
       StdOut.println();

       StdOut.println ("Reverse: Before: " + Arrays.toString(list1 ) );
       reverseArray (list1);
       StdOut.println (" After: " + Arrays.toString (list1) + "\n" );

       StdOut.println ("Reverse: Before: " + Arrays.toString(list2 ) );
       reverseArray (list2);
       StdOut.println (" After: " + Arrays.toString (list2) + "\n");

       StdOut.println ("Reverse: Before: " + Arrays.toString(list3 ) );
       reverseArray (list3);
       StdOut.println (" After: " + Arrays.toString (list3) + "\n");

       StdOut.println ("Reverse: Before: " + Arrays.toString(list4 ) );
       reverseArray (list4);
       StdOut.println (" After: " + Arrays.toString (list4) + "\n");

       StdOut.println ("Reverse: Before: " + Arrays.toString(list5 ) );
       reverseArray (list5);
       StdOut.println (" After: " + Arrays.toString (list5) + "\n");

       mergeArrayTests();
       StdOut.println("***************************************************************");
       StdOut.println(" Output was not verified to be correct by this program. ");
       StdOut.println(" It is up to you to review the output and verify the results");
      
   }
}

Java Eclipse

Please do sections marked TODO and explain code if possible.

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

I've tried to write in very simple way. If you didnt get it, write in comments

import java.util.Arrays;
import stdlib.*;


public class Temp {

/**
* As a model for Problem 1, here are two functions to find the minimum value of an array of ints
* an iterative version and a recursive version
*
* precondition: list is not empty
/** iterative version */
public static double minValueIterative (int[] list) {
int result = list[0];
int i = 1;
while (i < list.length) {
if (list[i] < result) result = list[i];
i = i + 1;
}
return result;
}

/** recursive version
* Find minimum of a list of size N starting at location 0
* Smaller problem is : Find minimum of list of size N-1, starting at 0
*
* precondition: list is not empty
*/
public static int minValueRecursive (int[] list) {
return minValueHelper (list, list.length);
}
private static int minValueHelper (int[] list, int n) {
if (n == 1) // the list of size 1 is the single element list[0]
return list[0]; // the minimum of this list is just that element.

// else: find minimum of smaller list

int minOfSmallerList = minValueHelper( list, n-1); // recursive call, 'smaller' list

// now compare min of smaller list to 'last' element of this list
// the list is of size n, the 'last' element is at position n-1
// because indexes start at 0.
int theMin;

if ( list[n-1] < minOfSmallerList)
theMin = list[n-1];
else
theMin = minOfSmallerList;

return theMin;
}

/**
* PROBLEM 1: Translate the following summing function from iterative to
* recursive.
*
* You should write a helper method. You may not use any "fields" to solve
* this problem (a field is a variable that is declared "outside" of the
* function declaration --- either before or after).
*
* Precondition: a list of ints, - maybe empty!
* Postcondition: the sum of the positive values is returned
*/
public static int sumOfPositives (int[] a) {
int result = 0;
int i = 0;
while (i < a.length) {
if ( a[i] > 0)
result = result + a[i];
i = i + 1;
}
return result;
}

public static int sumOfPositivesRecursive (int[] a) {
return SOPHelper(a, a.length); // TODO 1 replace this by a call to your helper function, then write the helper function below
  
}
public static int SOPHelper(int[]a, int n){
if(n==0)
return 0;
int s=SOPHelper(a, n-1);
if(a[n-1]>0)
return s+a[n-1];
else return s;
}
// this would be a good place to put the helper function for #1
/**
* Here is an in-place iterative function to reverse an array.
*
* in-place means: we don't create an extra array (to simplify coding)
*
*/
public static void reverseIterative (int[] a) {
int hi = a.length - 1;
int lo = 0;
while (lo < hi) {
int loVal = a[lo];
int hiVal = a[hi];
a[hi] = loVal;
a[lo] = hiVal;
lo = lo + 1;
hi = hi - 1;
}
}
/*
* * PROBLEM 2: Convert the above iterative function to a recursive version
*
* You should write a helper method. You may not use any "fields" to solve
* this problem (a field is a variable that is declared "outside" of the
* function declaration --- either before or after).
* You may not use any other methods
*
* Your helper function must be parameterized to allow a smaller problem to
* be specified. How do you reverse an array of size N?
* (the answer is NOT: reverse an array of size N-1 ! )
*/
public static void reverseArray (int[] a) {
reverseHelper(a,0,a.length-1);
return; // TODO 2 replace this by a call to your recursive helper function, then write the helper function below
}

private static void reverseHelper(int[] a, int start, int end) {
if(start>=end)
return;
reverseHelper(a, start+1, end-1);
int temp=a[start];
a[start]=a[end];
a[end]=temp;

}

// a good place for your helper function for #2
/**
* PROBLEM 3: merge together two sorted arrays of ints into a new array.
*
* Example1 merge: [-1 3 5 7 ] with [ 2 4 6 8] would yield [-1 2 3 4 5 6 7 8]
* Example2 merge: [1 6 ] with [ 2 3 8 9] would yield [1 2 3 6 8 9]
* There is no guarantee about the size of either array. When/if you run out of elements in
* either array, copy all the remaining elements from the nonempty array to the the new array
* preconditions:
* both arrays are sorted low to high
* there are no duplicate values among the two arrays
* either array may be empty
* postcondition: return an array with all elements from both arrays sorted from low to high
*
* You may not use any additional methods, sorting routines etc
* For full credit, your solution may only go through each array one time ( so in particular - no nested loops)
*
* You will need to create a new array inside the function
* You do not have to write this recursively.
*/

public static int[] mergeArrays( int[] a, int[] b) {

int[] answer = new int[a.length+b.length];
int i=0,j=0,k=0;
while(i<a.length || j<b.length){
if(i>=a.length || (j<b.length && a[i]>b[j])){
answer[k++]=b[j++];
}
else answer[k++]=a[i++];
}
return answer; // ToDo 3 . Fix this.
}


/*
* exercising functions and main.
* There are no Todo's for you in the code below.
*/
public static void mergeArrayTests() {

int a[] = new int[] {1,3,5,7,9,11};
int b[] = new int[] {2,4,6};
int[] combinedArray = mergeArrays( a,b);
System.out.println("merging: "+ Arrays.toString(a) + " " + Arrays.toString(b));
System.out.println(" --> " + Arrays.toString(combinedArray));

int c[] = new int[] {1,3,5,7,9,11};
int d[] = new int[] {2,4};
combinedArray = mergeArrays( c,d);
System.out.println("merging: "+ Arrays.toString(c) + " " + Arrays.toString(d));
System.out.println(" --> " + Arrays.toString(combinedArray));

int e[] = new int[] {1,3,5,7,9,11};
int f[] = new int[] {};
combinedArray = mergeArrays( e,f);
System.out.println("merging: "+ Arrays.toString(e) + " " + Arrays.toString(f));
System.out.println(" --> " + Arrays.toString(combinedArray));

int g[] = new int[] {3,11};
int h[] = new int[] {2,4,6,8,10};
combinedArray = mergeArrays( g,h);
System.out.println("merging: "+ Arrays.toString(g) + " " + Arrays.toString(h));
System.out.println(" --> " + Arrays.toString(combinedArray));
}

public static void main (String[] args) {

System.out.println(" This main function calls your functions for a variety of inputs");
System.out.println(" and simply prints the results");
System.out.println(" It does NOT check to see if your functions return the correct values");
System.out.println(" It is up to you to review the output and verify the results");
System.out.println("***************************************************************");
int[] list0 = new int[] {};
int[] list1 = new int[] { 5 };
int[] list2 = new int[] { 3, 4 };
int[] list3 = new int[] { -2, 3, -4 };
int[] list4 = new int[] { -1, -2, -4, -5 };
int[] list5 = new int[] { 6, 1, 2, -3, 8 };

System.out.format(" list: %s sum of positives: %d\n",Arrays.toString(list0), sumOfPositivesRecursive (list0));
System.out.format(" list: %s sum of positives: %d\n",Arrays.toString(list1), sumOfPositivesRecursive (list1));
System.out.format(" list: %s sum of positives: %d\n",Arrays.toString(list2), sumOfPositivesRecursive (list2));
System.out.format(" list: %s sum of positives: %d\n",Arrays.toString(list3), sumOfPositivesRecursive (list3));
System.out.format(" list: %s sum of positives: %d\n",Arrays.toString(list4), sumOfPositivesRecursive (list4));
System.out.format(" list: %s sum of positives: %d\n",Arrays.toString(list5), sumOfPositivesRecursive (list5));
System.out.println();

System.out.println ("Reverse: Before: " + Arrays.toString(list1 ) );
reverseArray (list1);
System.out.println (" After: " + Arrays.toString (list1) + "\n" );

System.out.println ("Reverse: Before: " + Arrays.toString(list2 ) );
reverseArray (list2);
System.out.println (" After: " + Arrays.toString (list2) + "\n");

System.out.println ("Reverse: Before: " + Arrays.toString(list3 ) );
reverseArray (list3);
System.out.println (" After: " + Arrays.toString (list3) + "\n");

System.out.println ("Reverse: Before: " + Arrays.toString(list4 ) );
reverseArray (list4);
System.out.println (" After: " + Arrays.toString (list4) + "\n");

System.out.println ("Reverse: Before: " + Arrays.toString(list5 ) );
reverseArray (list5);
System.out.println (" After: " + Arrays.toString (list5) + "\n");

mergeArrayTests();
System.out.println("***************************************************************");
System.out.println(" Output was not verified to be correct by this program. ");
System.out.println(" It is up to you to review the output and verify the results");
  
}
}

Add a comment
Know the answer?
Add Answer to:
import java.util.Arrays; import stdlib.*; public class CSC300Homework4 {    /**    * As a model for...
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
  • package homework; import java.util.Arrays; import stdlib.*; /** CSC300Homework4 version 1.0 * *    * * Find...

    package homework; import java.util.Arrays; import stdlib.*; /** CSC300Homework4 version 1.0 * *    * * Find the 3 Sections marked TODO: * * TODO #1: SumOddsRecursive * TODO #2: ReverseArray * TODO #3: MergeArrays * * You must not add static variables. You MAY add static functions. * * It is okay to add functions, such as * * <pre> * public static double sumOfOddsHelper (double[] list, int i) { * </pre> * * but it is NOT okay to...

  • Java Given the array, which has been converted to a linked list, I need to invoke...

    Java Given the array, which has been converted to a linked list, I need to invoke a remove method to remove a number from the list. The output for the first array should come out like this Now list1 = 24->18->3-7->null Now list2 = 31->-9->5->21->4->0->8->null Now lsit3 = 5->0->1->null but i keep getting this output Now list1= 12->3->7->null Now list2= -7->null Now list3= 5->0->1->null int arr1[] = {24, 18, 12, 3, 7}; int arr2[] = {31, -9, 5, 21, 4,...

  • 5. Given the following definition of class Node: class Node { public int item; public Node...

    5. Given the following definition of class Node: class Node { public int item; public Node next; public Node ( int i, Node n ) { item = i; next = n; }; } and the following declarations: Node list, p, q; Assume the structure starts as below. Draw the structure created by executing the following statements. Each part is independent. list 1 2 3 4 5   [2] a) p = list; q = null; while ( p != null...

  • Code in java Using the template below: public class Lab03 { public static void main(String[] args)...

    Code in java Using the template below: public class Lab03 { public static void main(String[] args) { ArrayList<Integer> list1 = new ArrayList<Integer>(); Collections.addAll(list1, 1, 3, 5, 5 ); ArrayList<Integer> list2 = new ArrayList<Integer>(); Collections.addAll(list2, 3, 7, 3, 2, 4 ); ArrayList<Integer> result1= uniqueUnion(list1,list2); System.out.println(result1); Integer[] array = new Integer[]{ 29, 28, 27, 16, 15, -14, 3, -2, 2}; ArrayList<Integer> arrayList = new ArrayList<Integer>(Arrays.asList(array)); System.out.printf("The average is: %.2f%n", averagePositive(arrayList)); } // end main public static ArrayList<Integer> uniqueUnion(ArrayList<Integer> list1, ArrayList<Integer> list2) {...

  • import java.util.Arrays; public class lab {    public static void main(String args[])    {    int...

    import java.util.Arrays; public class lab {    public static void main(String args[])    {    int arr[] = {10, 7, 8, 9, 1, 5,6,7};    int arr2[] = {9, 8, 7, 6, 5, 4, 3, 2, 1};    int arr3[] = {1, 3, 5, 3, 2, 6, 20};    quicksort(arr,0,arr.length-1);    quicksort(arr2,0,arr2.length-1);    quicksort(arr3,0,arr3.length-1);    System.out.println(Arrays.toString(arr));    System.out.println(Arrays.toString(arr2));    System.out.println(Arrays.toString(arr3));       }    private static int partition(int[] items,int low, int high)    {    int i=0;    int j=0;...

  • C++ comment code Comment the following code #include <iostream> using namespace std; class Node { public:...

    C++ comment code Comment the following code #include <iostream> using namespace std; class Node { public: Node(int val); int value; Node* next; }; Node::Node(int val){ value = val; } class List { public: List(); // Uncomment the line below once you're ready List(List &other); void push_front(int value); bool pop_front(int &value); void push_back(int value); bool pop_back(int &value); int at(int index); void insert_at(int index, int value); void remove_at(int index); int size(); private: // other members you may have used Node* head; Node*...

  • Java Programming: The following is my code: import java.util.Arrays; public class KWArrayList<E> {    // Data...

    Java Programming: The following is my code: import java.util.Arrays; public class KWArrayList<E> {    // Data fields    /** The default initial capacity */    private static final int INITIAL_CAPACITY = 10;       /** The underlying data array */    private E[] theData;       /** The current size */    private int size = 0;       /** The current capacity */    private int capacity = 0;       @SuppressWarnings("unchecked")    public KWArrayList() {        capacity...

  • Writing a method retainAll for Circular Doubly-Linked List: I am working on an assignment creating a...

    Writing a method retainAll for Circular Doubly-Linked List: I am working on an assignment creating a Circular Doubly Linked List and am having serious trouble creating a method retainAll. Here's the code, and my attempt. Initialization: public class CDoublyLinkedList {    private class Node {        private Object data; //Assume data implemented Comparable        private Node next, prev;        private Node(Object data, Node pref, Node next)        {            this.data = data;       ...

  • import java.util.Random; import java.util.ArrayList; /** * */ public class hw5_task8 { public static void main(String[] args)...

    import java.util.Random; import java.util.ArrayList; /** * */ public class hw5_task8 { public static void main(String[] args) { int[] grades = randomIntArr(10); printIntArray("grades", grades); ArrayList<Integer> indexesF_AL = selectIndexes_1(grades); System.out.println(" indexesF_AL: " + indexesF_AL); int[] indexesF_Arr = selectIndexes_2(grades); printIntArray("indexesF_Arr",indexesF_Arr); } public static int[] randomIntArr(int N){ int[] res = new int[N]; Random r = new Random(0); for(int i = 0; i < res.length; i++){ res[i] = r.nextInt(101); // r.nextInt(101) returns an in in range [0, 100] } return res; } public static void...

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