Csci 161 test 1

¡Supera tus tareas y exámenes ahora con Quizwiz!

1. In the main( ) method of the Client Class you have created a SinglyLinkedList of chars: SinglyLinkedList<Character> list = new SinglyLinkedList<>( ); Write the complete, syntactically correct, Java method that would remove the ith node in list. Your method must be written: a. As a member of the Client Class that can be called by the main( ) method. b. Where the main( ) method has created an instance of the SinglyLinkedList Class as defined in the textbook. c. Where the SinglyLinkedList Class has no additional methods added. d. So that no value is return by the method. e. So that the head node in the SinglyLinkedList is considered to be at index zero. f. Write your method so that it correctly deals with all possible errors. public static void removeSSL(SinglyLinkedList<Character> list, int indexToRemove) throws InvalidParameterException {

// // check for index out of bounds // if (indexToRemove < 0 || indexToRemove >= list.size()) { throw new InvalidParameterException("Invalid Index"); } int initialSize = list.size(); // required since size changes char temp; for (int i = 0; i < initialSize; i++) { temp = list.removeFirst(); if (i != indexToRemove) { list.addLast(temp); } } }

1. Write a toString( ) method for the SinglyLinkedList Class as defined in the textbook. Write your toString( ) method so that: a. It is a member of the SinglyLinkedListClass b. It meets the requirements of a toString( ) method as defined in this course. For your reference, the beginning of the SinglyLinkedList Class is: public class SinglyLinkedList<E> { public static class Node<E> { private E element; private Node<E> next; public Node(E e, Node<E> n ) { element = e; next = n; } public E getElement( ) { return element; } public Node<E> getNext( ) { return next; } public void setNext( Node<E> n ) { next = n; } } private Node<E> head = null; private Node<E> tail = null; private int size = 0;

// // make use of access to the Node // more efficient // public String toString() { String returnStr = getClass().getName() + "@ count = " + size + ": head => "; Node<E> cursor = head; while (cursor != null) { returnStr += cursor.getElement().toString() + " => "; cursor = cursor.getNext(); } returnStr += "tail"; return returnStr; }

2. Exam function, E, is defined as follows: n - 10 if n > 100 E(n) = E( E( n + 11 ) ) if n <= 100 a. Write a complete and syntactically correct recursive Java method to compute E( n ) the sum of integer values. b. Draw the recursive trace for E( 98 ) ?

// E is actually known as the McCarthy91 function. public static int McCarthy91( int n ) { // base case n > 100 if ( n > 100 ) return n - 10; // general case n <= 100 return McCarthy91( McCarthy91( n + 11) ); }

Write a recursive method that returns the number of even integers in an array of int.

// Space efficent // Requires class variable private static int level3 = 0; public static int numEven3( int[] array ) { if ( array.length == 0 ) return 0; if ( array.length == 1 ) if ( array[0] % 2 == 0 ) return 1; else return 0; if ( array.length == level3 + 1 ) return 0; level3++; if ( array[ level3 ] % 2 == 0 ) return 1 + numEven3( array ); return numEven3( array ); }

1. Write the complete, syntactically correct, generic Java code for the addLast( E e ) method for the DoublyLinkedList class as defined in the textbook. The start of the DoublyLinkedList class is given below. If your answer includes any methods defined in the DoublyLinkedList class that are not given below then you must provide the code for those methods as well. public class DoublyLinkedList<E> { private static class Node<E> { private E element; private Node<E> prev; private Node<E> next; public Node(E e, Node<E> p, Node<E> n) { element = e; prev = p; next = n; } public E getElement() { return element; } public Node<E> getPrev() { return prev; } public Node<E> getNext() { return next; } public void setPrev(Node<E> p) { prev = p; } public void setNext(Node<E> n) { next = n; } } private Node<E> header; // header sentinel private Node<E> trailer; // trailer sentinel private int size = 0;

// Standalone method that does not rely on addBetween( ) public void addLast2(E e) { Node<E> newNode = new Node<>( e, null, null ); newNode.setNext( trailer ); newNode.setPrev( trailer.getPrev() ); newNode.getPrev().setNext( newNode ); trailer.setPrev( newNode ); size++; }

6. Write the complete, syntactically correct, generic Java code for the addLast( E e ) method for the DoublyLinkedList class as defined in the textbook. The start of the DoublyLinkedList class is given below. If your answer includes any methods defined in the DoublyLinkedList class that are not given below then you must provide the code for those methods as well. public class DoublyLinkedList<E> { private static class Node<E> { private E element; private Node<E> prev; private Node<E> next; public Node(E e, Node<E> p, Node<E> n) { element = e; prev = p; next = n; } public E getElement() { return element; } public Node<E> getPrev() { return prev; } public Node<E> getNext() { return next; } public void setPrev(Node<E> p) { prev = p; } public void setNext(Node<E> n) { next = n; } } private Node<E> header; // header sentinel private Node<E> trailer; // trailer sentinel private int size = 0;

// Standalone method that does not rely on addBetween( ) public void addLast2(E e) { Node<E> newNode = new Node<>( e, null, null ); newNode.setNext( trailer ); newNode.setPrev( trailer.getPrev() ); newNode.getPrev().setNext( newNode ); trailer.setPrev( newNode ); size++; }

1. Assume that you have create the following three complete and syntactically correct Java classes where each class has defined appropriate setter and getter methods for each of its instance variable: Employee Class with instance variables: private int id private String name Salaried Class as subclass (child class) of Employee with instance variables: private String title private int salary Hourly Class as subclass (child class) of Employee with instance variables: private String position private double hourlyRate Also assume that in the Client Class main method you have already created and populated and array of type Employee named list with several instances of Salaried Class objects randomly interspaced with several instance of Hourly Class objects. Write the syntactically correct Java code segment that will correctly give a 25% raise to each entry in list. Write your code segment so that after your code segment the contents of list will correctly reflect the 25% raise.

// give everyone a 25% raise for ( int i = 0; i < employeeList.length; i++) { if ( employeeList[i] != null ) { if ( employeeList[i] instanceof Salaried ) { Salaried tempSalaried = (Salaried) employeeList[i]; int oldSalary = tempSalaried.getSalary(); int newSalary = (int) (oldSalary * 1.25); tempSalaried.setSalary( newSalary ); } else { Hourly tempHourly = (Hourly) employeeList[i]; double oldRate = tempHourly.getHourlyRate(); double newRate = oldRate * 1.25; tempHourly.setHourlyRate( newRate ); }}}

1. For your reference the start of the generic SinglyLinkedList class is: 2. 3. public class SinglyLinkedList<E> { 4. private static class Node<E> { 5. private E element; 6. private Node<E> next; 7. public Node(E e, Node<E> n) { 8. element = e; 9. next = n; 10. } 11. public E getElement() { return element; } 12. public Node<E> getNext() { return next; } 13. public void setNext(Node<E> n) { next = n; } 14. } 15. private Node<E> head = null; 16. private Node<E> tail = null; 17. private int size = 0; 18. // ... 19. // you should know the other members/methods 20. // of SinglyLinkedList class 21. // 22. Xxx 1. Write a method named addLast to insert an element at the end of a generic SinglyLinked List assuming that the start of the generic SinglyLinked List class definition is

1. public void addLast(E e) { // adds element e to the end of the list 2. Node<E> newest = new Node<>(e, null); // node will eventually be the tail 3. if (isEmpty()) 4. head = newest; // special case: previously empty list 5. else 6. tail.setNext(newest); // new node after existing tail 7. tail = newest; // new node becomes the tail 8. size++; 9. }

What is multiple recursion? Give an example.

A recursive method exhibits multiple recursion when the general case makes more than two recursive calls. The calls don't need to be in the same statement they just all need to be executed, e.g. with a common block. The English ruler in textbook is an example. Most clever example: Public static int tripleFibonacci( int n ) if ( n <= 1 ) return 1; else return tripleFibonacci( n -3 ) + tripleFibonacci( n -2 ) + tripleFibonacci( n - 1) Will accept binary recursion at lower limit: The classic example of binary recusion it the Fibonnici: public static long Fibonacci( int n ) { if ( n <= 1 ) return n; else return ( fibonacci( n - 2 ) + fibonnaci( n -1 ); }

Provide a complete definition/description of a recursive method that includes: a. a definition of what a recursive method is b. a descrption of what every recursive method must contain.

A recursive method is a method that makes one or more calls to itself during execution. Every recursive method must contain a base case that stop the recursion a general case that make the recursive class with a parameter than make the problem smaller towards the base case.

1. What are the advantages and/or disadvantages of using sentinels in a doubly linked list?

Advantages - Head and tail pointers never change - Insertion and delations always between nodes so code does not require special cases Disadvantages - Extra memory used by sential nodes, minor since any object pointers would be null

What are the advantages and/or disadvantages of using sentinels in a doubly linked list?

Advantages: -head and tail pointers never change -insertion and delations are always between nodes so code does not require special cases Disadvantages -extra memory used by sentinel nodes, minor since any object pointers would be null

1. For the following algorithm: a. What is the mathematically precise number of primitive operations performed in the best case? b. What is the mathematically precise number of primitive operations performed in the worst case? c. What is the Big-Oh for the running time? // // Algorithm for question 6. // public static void exam1a( int[ ] arr ) { boolean x = true; 1 int i = 0; 1 while ( x && i < arr.length ) 2 { x = false; 1 for ( int j = 0; j < arr.length - 1; j++ ) { 1 2 if ( arr[ j ] > arr[ j + 1 ] ) { 4 int temp = arr[ j ]; 2 arr[ j ] = arr[ j + 1 ]; 4 arr[ j + 1 ] = temp; 2 x = true; 1 }}}}

Best case: Array already in order PreLoop 2 while loop executes once, if never true 4 * n for loop executes once, if never true 1 * 15 4n + 17 Worst case: Array in reverse order PreLoop 2 while loop executes n times (actually n-1) 4 * n for loop executes n times (acutally n-1) n * 15 15n^2 + 4n + 2 BigOh = O ( n^2 )

1. Rearrange following functions in a verital list by asymptotic growth rate with the most desirable growth rate at the top and the least desirable growth rate at the bottom: a. 4n logn + 2n b. 210 c. 2logn d. 3n + 100logn e. 4n f. 2n g. n2 + 10n h. n3 i. nlogn

Constant O( 1 ) 210 B Log O( log2n ) Linear O( n ) 2logn = n 3n + 100logn 4n C D E Log Linear O( n log2n ) nlogn 4n logn + 2n I A Quadratic O( n2 ) n2 + 10n G Polynominal, cubic and higher O( n3+ ) n3 H Exponential bn, b is often 2 2n F

1. The textbook discusses seven functions for describing the execution time of algorithms. List these seven functions vertically from best (top) to worst (bottom).

Constant O( 1 ) Log O( log n ) more correctly O( log2 n ) Linear O( n ) Log-Linear O( n log n) again, more correctly O( n log2 n ) Quadratic O( n^2 ) Polynominal O( n^p ), for p > 2 Exponential ( b^n )

1. The textbook discusses seven functions for describing the execution time of algorithms. List these seven functions from best to worst.

Constant O( 1 ) Log O( log n ) more correctly O( log2 n ) Linear O( n ) Log-Linear O( n log n) again, more correctly O( n log2 n ) Quadratic O( n^2 ) Polynominal O( n^p ), for p > 2 Exponential ( b^n ) for us b usually 2

2. The textbook discusses seven functions for describing the execution time of algorithms. List these seven functions from best to worst.

Constant O( 1 ) Log O( log n ) more correctly O( log2 n ) Linear O( n ) Log-Linear O( n log n) again, more correctly O( n log2 n ) Quadratic O( n^2 ) Polynominal O( n^p ), for p > 2 Exponential ( b^n ) for us b usually 2

1. The textbook discusses seven functions for describing the execution time of algorithms. List these seven functions from best to worst.

Constant O( 1 ) Log O( log2n ) Linear O( n ) n Log n O( n * log2n ) Quadratic O( n2 ) Polynomial O( c0 + c1n + c2n^2 + c3n^3 + ... + cin^i ) Exponential O( 2^n )

1. The textbook discusses seven functions for describing the execution time of algorithms. List these seven functions from best to worst.

Constant O( 1 ) Log O( log2n ) Linear O( n ) n Log n O( n * log2n ) Quadratic O( n2 ) Polynoninal O( c0 + c1n + c2n2 + c3n3 + ... + cini ) Exponential O( 2n )

1. The textbook discusses seven functions for describing the execution time of algorithms. List these seven functions vertically from best to worst with the best being listed at the top.

Constant O( 1 ) Log O( log2n ) Linear O( n ) n Log n O( n * log2n ) Quadratic O( n2 ) Polynoninal O( c0 + c1n + c2n2 + c3n3 + ... + cini ) Exponential O( 2n )

7. What are both the mathematically precise statement and the Big-Oh for the worst case running time of the following algorithm? 10 points public static void exam1( int [ ] array ) { int a; int b; for ( int c = 0; c < array.length; c++ ) { b = 0; for ( int d = 1; d < array.length - c; d++ ) { if ( array[ d ] > array[ b ] ) b = d; } for ( int e = array.length - c; e < array.length; e++ ); a = array[ b ]; array[ b ] = array[ array.length - c - 1 ]; array[ array.length -c - 1 ] = a; } }

Replaced the parameter identifier with x to give more room on right. public static void exam1( int [ ] x ) { int a; int b; for ( int c = 0; c < x.length; c++ ) 1 2 { b = 0; 0 1 for ( int d = 1; d < x.length - c; d++ ) 0 1 3 { if ( x[ d ] > x[ b ] ) 0 0 3 b = d; 0 0 0/1 } for ( int e = x.length - c; e < x.length; e++ ); 0 2 2 a = x[ b ]; 0 2 x[ b ] = x[ x.length - c - 1 ]; 0 5 x[ x.length -c - 1 ] = a; 0 4 } } 1 17 9 9 n^2 + 17 n + 1 O( n^2 )

How can you avoid throwing ClassCastException errors?

Use instanceof to determine if the cast can be made before attempting the cast.

All subtypes of RuntimeException in java are officially treated as ________ exceptions, and any exception type that is not part of the RuntimeException is a _______ exception.

checked; unchecked

You have two algorithms, one with O(n) and one with O(n^2). under what circumstances, if any, might the algorithm with O(n^2) be a better choice than the algorithm with O(n)? provide an example as part of your answer

if the coefficients and/or constants on the O(n) are large enough they may overshadow the effect of n^2 for a small enough value of n. Example: O(n) comes from 10000*n O(n^2) comes from n^2 from n = 1 to n = 9,999 n^2 is less than 10000

1. Write a complete and syntactically correct Java toString( ) method for a generic SinglyLinkedList. Write this method: a. As a member of the SinglyLinkedList class. b. So that it meets the requirement of a toStirng( ) method presented in class. c. If your toString( ) method calls any methods from the SinglyLinkedList class not list in the partial class definition given below, you must write those methods as well. The start of the generic SinglyLinkedList Class definition is: public class SinglyLinkedList<E> { private static class Node<E> { private E element; private Node<E> next; public Node(E e, Node<E> n) { element = e; next = n; } public E getElement() { return element; } public Node<E> getNext() { return next; } public void setNext(Node<E> n) { next = n; } } private Node<E> head = null; private Node<E> tail = null; private int size = 0;

public String toString( ) { String rtnString = getClass( ).getName( ) + "@" + "size = " + size + " head=>>"; Node<E> temp = head; while ( temp != null ){ rtnString += " " + temp.getElement().toString(); temp = temp.next; } rtnString += " <<= tail "; return rtnString; }

1. What are both the mathematically precise statement and the Big-Oh for the worst case running time of the following algorithm? 10 points

int n = first.length; 1 int total = 0; 1 for ( int i = 0; i < n; i++ ) 1 2 { total += first[ i ]; 3 } for ( int j = 0; j < n; j++ ) 1 2 { total += second[ j ]; 3 } for ( int k = 0; k < n; k++ ) 1 2 { total += third[ k ]; 3 } for ( int l = 0; l < n; l++ ) 1 2 { total += fourth[ l ]; 3 } return total; 1 } 7 20n 20 n + 7 O( n )

What are both the mathematically precise statement and the Big-Oh for the running time of the following algorithm: public static double xyz(double[]x){ int y = x.length; double a = x[0]; for (int i = 1; i < y; i++;){ if(x[i]>y) a = x[i]; } return y; }

int y = x.length; 1 double a = x [ 0 ]; 2 for ( int i = 1; i < y; i++ ) 1 to initialize i loop (n-1) times 1 for comparison { if ( x[ i ] > y ) 2 a = x[ i ]; 2 1 for i++ } return y; 1 } 1 + 2 + 1 + ( n - 1 ) * 6 + 1 5 + 6n - 6 6n - 1

A class that is defined inside of another class is termed a __________ class. If the class defined inside another class is designated as non-static it is commonly known as an ______ class.

nested; inner

Write a method named removeFirst that removes the first node in a generic Singly Linked List and returns the element in the node being removed assuming that the start of the generic SinglyLinked List class definition is: public class SinglyLinkedList<E> { private static class Node<E> { private E element; private Node<E> next; public Node(E e, Node<E> n) { element = e; next = n; } public E getElement() { return element; } public Node<E> getNext() { return next; } public void setNext(Node<E> n) { next = n; } } private Node<E> head = null; private Node<E> tail = null; private int size = 0;

public E removeFirst( ) { if ( isEmpty( ) ) return null; E answer = head.getElement( ); head = head.getNext( ); size--; if ( size == 0 ) tail = null; return answer; }

1. Write the complete, generic and syntactically correct Java removeLast method for a generic SinglyLinkedList. Write this method: a. b. As a member of the SinglyLinkedList class. c. d. So that it returns the element that is in the node being removed from the list. e. The start of the generic SinglyLinkedList Class definition is: public class SinglyLinkedList<E> { private static class Node<E> { private E element; private Node<E> next; public Node(E e, Node<E> n) { element = e; next = n; } public E getElement() { return element; } public Node<E> getNext() { return next; } public void setNext(Node<E> n) { next = n; } } private Node<E> head = null; private Node<E> tail = null; private int size = 0;

public E removeLast() { if ( size == 0 ) return null; else if ( size == 1 ) { E element = head.getElement(); head = null; tail = null' count = 0; return element; } else { Node temp = head; while ( temp.next.next != null ) temp = temp.next; E element = tail.getElement(); tail = temp; temp.next = null; count--; return element; }

1. Write the complete and syntactically correct Java removeLast method for a generic SinglyLinkedList. Write this method: a. As a member of the SinglyLinkedList class. b. So that it returns the element that is in the node being removed from the list. The start of the generic SinglyLinkedList Class definition is: public class SinglyLinkedList<E> { private static class Node<E> { private E element; private Node<E> next; public Node(E e, Node<E> n) { element = e; next = n; } public E getElement() { return element; } public Node<E> getNext() { return next; } public void setNext(Node<E> n) { next = n; } } private Node<E> head = null; private Node<E> tail = null; private int size = 0;

public E removeLast(){ if ( size == 0 ) return null; else if ( size == 1 ) { E element = head.getElement(); head = null; tail = null' count = 0; return element; } else { Node temp = head; while ( temp.next.next != null ) temp = temp.next; E element = temp.getElement(); tail = temp; temp.next = null; size--; return element; }

Write a method that returns a pointer to the next-to-last node in a generic singly linked list in which the last node is indicated by a null next reference

public Node<E> nextToLast(ListBag<E> list){ if(list.size<2) return null; else{ Node temp = list.head; while(temp.next.next != null) temp = temp.next; return temp; } }

1. What are both the mathematically precise statement and the Big-Oh for the worst case running time of the following algorithm?

public static int exam2( int [ ] first, int[ ] second, int[ ] third, int[ ] fourth ) { int n = first.length; 1 int total = 0; 1 for ( int i = 0; i < n; i++ ) 1 2 { total += first[ i ]; 3 for ( int j = 0; j < n; j++ ) 1 2 { total += second[ j ]; 3 } } for ( int k = 0; k < n; k++ ) 1 2 { for ( int l = 0; l < n; l++ ) 1 2 { total += fourth[ l ]; 3 } total += third[ k ]; 3 } return total; 1 } 5 12n 10n^2 10n^2 + 12n + 5 O( n^2 )

1. Write the complete and syntactically correct Java toString( ) method for a generic SinglyLinkedList that displays the contents of the list that includes the class name, the values of all of the members, and the contents of each node. Keep in mind that the toString( ) method that you are writing is a member of the generic SinglyLinkededList class. The start of the generic SinglyLinkedList Class definition is: public class SinglyLinkedList<E> { private static class Node<E> { private E element; private Node<E> next; public Node(E e, Node<E> n) { element = e; next = n; } public E getElement() { return element; } public Node<E> getNext() { return next; } public void setNext(Node<E> n) { next = n; } } private Node<E> head = null; private Node<E> tail = null; private int size = 0; // ... // you should know the other members/methods // of SinglyLinkedList class //

public String toString() { String returnString = getClass().getName() + "@size = " + size + ":head->"; Node temp = head; for (int i = 0; i < size; i++ ) { returnString += " " + temp.element.toString(); temp = temp.next; } returnString += " <-tail"; return returnString; }

5. Write the complete and syntactically correct Java toString( ) method for a generic SinglyLinkedList that displays the contents of the list that includes the class name, the values of all of the members, and the contents of each node. Keep in mind that the toString( ) method that you are writing is a member of the generic SinglyLinkededList class. The start of the generic SinglyLinkedList Class definition is: public class SinglyLinkedList<E> { private static class Node<E> { private E element; private Node<E> next; public Node(E e, Node<E> n) { element = e; next = n; } public E getElement() { return element; } public Node<E> getNext() { return next; } public void setNext(Node<E> n) { next = n; } } private Node<E> head = null; private Node<E> tail = null; private int size = 0; // ... // you should know the other members/methods // of SinglyLinkedList class //

public String toString() { String returnString = getClass().getName() + "@size = " + size + ":head->"; Node temp = head; for (int i = 0; i < size; i++ ) { returnString += " " + temp.element.toString(); temp = temp.next; } returnString += " <-tail"; return returnString; }

1. Write a complete, generic and syntactically correct Java method for the ArrayBag class that removes and returns the element at a specific index in the ArrayBag. Write the method so that it: a. Has the signature T remove( int index ) b. Returns the element stored at the index being removed c. Fills in the "empty slot" in the array by shifting values to the left d. Throws an InvalidParameterException if it is passed an invalid parameter e. Is written as efficiently as possible f. If your method calls any methods from the ArrayBag class not list in the partial class definition given below, you must write those methods as well. public class ArrayBag<T> implements Bag<T> { private T[] list; // the array of ints private int count;

public T remove( int index ){ if ( count == 0 ) return null; if ( index < 0 || index > count - 1 ) throw new ArrayIndexOutOfBoundsException( "Index out of bounds" ); T temp = list[ index ]; for ( int i = index; i < ( count - 1 ); i++ ) { list[i] = list[ i + 1 ]; } count--; return temp; }

Write the add method for the generic ArrayBag class assuming that the start of the ArrayBag class definition is: public class ArrayBag <T> implements Bag <T> { private T[ ] bag; // the array of objects private int count; // number of object in the array

public boolean add(T item) { try{ if( count == bag.length ) { T[] temp = (T[]) new Object[bag.length*2]; int i; for(i = 0; i < bag.length; i++) temp[i] = bag[i]; bag = temp; temp = null; } bag[count] = item; count++; return true; } catch ( OutOfMemoryError oome ){ System.err.println( "In ArrayBag, add failed: " + oome.getMessage() ); return false; } }

1. ArrayBag class equals method

public boolean equals( Object o ) { if ( !( o instanceof ArrayBag ) ) return false; ArrayBag s = ( ArrayBag ) o; if ( count != s.size() ) return false; for ( int i = 0; i < count; i++ ) { if ( !list[i].equals( s.list[i] ) ) return false; } return true; }

1. Write a complete and syntactically correct Java Class named Basketball that implements the following concepts of an basketball player: - The Class is a subclass of the Player Class - The Class keeps track of the players's height as a double. - The Class has a single overload constructor that includes all of the necessary values to create a complete instance of the Class as parameter(s). You do not need a default constructor. - There are appropriate setter and getter methods for each member of the Class. - There is a toString method - There is an equals method

public class Basketball extends Player { private double height; public Basketball( String name, double height) { super( name ); this.height = height; } public void setHeight( double height ) { this.height = height; } public double getHeight( ) { return height; } public String toString() { return super.toString() + ":" + getClass().getName() + "@height = " + height; } public boolean equals( Object o ) { if ( !(o instanceof Basketball ) ) return false; Basketball b = ( Basketball ) o; return super.equals( b ) && Math.abs( height - b.height ) < .01; } }

1. Write a complete and syntactically correct Java Class named Contact that implements the following concept of an address book contact: - The Class keeps track of the contact's name as a String - The Class has the ability to keep track of the total number of instances of the Class that have been instantiated. - The Class has a single overload constructor that includes all of the necessary values to create a complete instance of the Class as parameter(s). You do not need a default constructor. - There are appropriate setter and getter methods for each member of the Class. - There is a toString method - There is an equals method

public class Contact { private String name; private static int contactCount = 0; public Contact( String name ) { this.name = name; contactCount++; } public void setName( String name ) { this.name = name; } public String getName( ) { return name; } public int getContactCount( ) { return contactCount; } public String toString( ) { return getClass( ).getName( ) + "@" + contactCount + ":" + name; } public boolean equals( Object o ) { if ( !( o instanceof Contact ) ) return false; Contact c = ( Contact ) o; return name.equalsIgnoreCase( c.name ); } }

1. Write a complete and syntactically correct Java Class named Contact that implements the following concept of an address book contact: - The Class keeps track of the contact's name as a String - The Class has the ability to keep track of the total number of instances of the Class that have been instantiated. - The Class has a single overload constructor that includes all of the necessary values to create a complete instance of the Class as parameter(s). You do not need a default constructor. - There are appropriate setter and getter methods for each member of the Class. - There is a toString method - There is an equals method

public class Contact { private static int numContacts = 0; private String name; public Contact( String name ) { this.name = name; } public void ( String name ) { this.name = name; } public String getName( ) { return name; } public int getNumContacts( ) { return numContacts; } public String toString( ) { Return getClass().getName() + "@" + Name + ":" + numContacts; public Boolean equals( Object o ) { if( !( o instanceOf Contact ) ) return false; contact c = (Contact) o; return name.equals( c.name ); }

1. Write a complete Java class named Dog that is a subclass of the Pet class and that has one instance variable, weight, of type int. Include an overload constructor and all other "normally" expected methods. You do not need to include a default constructor.

public class Dog extends Pet { private int weight; public Dog( String name, int weight ) { super( name ); this.weight = weight; } public void setWeight( int weight ) { this.weight = weight; } public double getWeight( ) { return weight; } public String toString( ) { return super.toString() + ":" + weight; } public boolean equals( Object o ) { if ( !( o instanceof Dog ) ) return false; Dog d = ( Dog ) o; return super.equals( d ) && ( weight == d.weight ); } }

1. Write a complete Java class named Dog that is a subclass of the Pet class and that has two instance variables: a. weight, of type double that hold the weight of the dog in pounds to the nearest quarter of a pound. b. dogCount, of type int that keeps a running count of all of the dog instances created. c. Include an overload constructor and all other "normally" expected methods. You do not need to include a default constructor.

public class Dog extends Pet { private int weight; public Dog( String name, int weight ) { super( name ); this.weight = weight; } public void setWeight( int weight ) { this.weight = weight; } public double getWeight( ) { return weight; } public String toString( ) { return super.toString() + ":" + weight; } public boolean equals( Object o ) { if ( !( o instanceof Dog ) ) return false; Dog d = ( Dog ) o; return super.equals( d ) && ( weight == d.weight ); } }

1. Write a complete and syntactically correct Java class for an Employee entity where: a. the class uses the interface from the previous question b. the Employee attributes are: i. name that is stored as a String ii. id that is stores as an int c. the class includes all of the "normally expected" methods

public class Employee implements EmployeeInterface { private String name; private int id; public Employee( ) { } public Employee( String name, int id ) { this.name = name; this.id = id; } @Override public String getName( ) { return name; }; @Override public void setName( String newName ) { name = newName; } @Override public int getId( ) { return id; } @Override public void setId( int newId ) { id = newId; } @Override public String toString( ) { return getClass( ).getName( ) + ":" + name + ":" + id; } @Override public boolean equals( Object o ) { if ( !( o instanceof Employee ) ) return false; Employee obj = ( Employee ) o; return name.equals( obj.name ) && id == obj.id; } }

1. Write a complete and syntactically correct Java Class named Employee that implements the following concept of an employee record: - The Class keeps track of the employee's name as a String - The Class has the ability to keep track of the total number of instances of the Class that have been instantiated. - The Class has a single overload constructor that includes all of the necessary values to create a complete instance of the Class as parameter(s). You do not need a default constructor. - There are appropriate setter and getter methods for each member of the Class. - There is a toString method - There is an equals method

public class Employee { private String name; private static int employeeCount = 0; public Employee( String name ) { this.name = name; employeeCount++; } public void setName( String name ) { this.name = name; } public String getName( ) { return name; } public int getEmployeeCount( ) { return employeeCount; } public String toString( ) { return getClass( ).getName( ) + "@" + employeeCount + ":" + name; } public boolean equals( Object o ) { if ( !( o instanceof Employee ) ) return false; Employee c = ( Employee ) o; return name.equalsIgnoreCase( c.name ); } }

1. Write a complete and syntactically correct Java Class named Friend that implements the following concepts of an address book friend contact: - The Class is a subclass of the Contact Class - The Class keeps track of the Friends birthday as an integer (e.g. 20170231). You do not need to check for valid birthdates. - The Class has a single overload constructor that includes all of the necessary values to create a complete instance of the Class as parameter(s). You do not need a default constructor. - There are appropriate setter and getter methods for each member of the Class. - There is a toString method - There is an equals method

public class Friend extends Contact { private int bDay; public Friend( String name, int bDay ) { super( name ); this.bDay = bDay; } public int getBDay ( ) { return bDay; } public void setBDay( ) { this.bDay = bDay; } public String toString( ) { return super.toString( ) + ":" + getClass().getName() + ":" + bDay; } public boolean equals( Object o ) { if( !( o instance of Friend ) ) return false; Friend f = (Friend) o; return super.equals( f ) && bDay == f.bDay; }

1. What are both the mathematically precise statement and the Big-Oh for the worst case running time of the following algorithm?

public static int exam3( int[ ] first, int [ ] second, int[ ] third, int [ ] fourth ) { int n = first.length; 1 int total = 0; 1 for ( int i = 0; i < n; i++ ) 1 2 { total += first[ i ]; 3 for ( int j = 0; j < n; j++ ) 1 2 { total += second[ j ]; 3 for ( int k = 0; k < n; k++ ) 1 2 { total += fourth[ k ]; 3 } } } for ( int l = 0; l < n; l++ ) 1 2 { total += third[ l ]; 3 } return total; 1 } 5 11n 6n^2 5n^3 5n^3 + 6n^2 + 11n + 5 O( n^3 )

1. Write a complete and syntactically correct Java Class named Friend that implements the following concepts of an address book friend contact: - The Class is a subclass of the Contact Class - The Class keeps track of the Friends birthday as an integer (e.g. 20170231). You do not need to check for valid birthdates. - The Class has a single overload constructor that includes all of the necessary values to create a complete instance of the Class as parameter(s). You do not need a default constructor. - There are appropriate setter and getter methods for each member of the Class. - There is a toString method - There is an equals method

public class Friend extends Contact { private int birthday; public Friend( String name, int birthday ) { super( name ); this.birthday = birthday; } public void setBirthday( int birthday ) { this.birthday = birthday; } public int getBirthday( ) { return birthday; } public String toString( ) { return super.toString( ) + getClass( ).getName( ) + "@" + birthday; } public boolean equals( Object o ) { if ( !( o instanceof Friend ) ) return false; Friend f = ( Friend ) o; return super.equals( f ) && birthday == f.birthday; } }

1. Assume that you have a complete and syntactically correct Java Class named Person that includes a single instance variable name of type String. Also assume that this Person Class contains all of the normally expected methods as defined in this course. Write a complete and syntactically correct Java Class named Friend that implements the following concepts of an address book friend contact: · The Class is a subclass of the Person Class · The Class keeps track of the Friends birthday as an integer (e.g. 20170231). You do not need to check for valid birthdates. · This Class uses an integer variable friendCount to keep track of the total number of friends that you have. · The Class has a single overload constructor that includes all of the necessary values to create a complete instance of the Class as parameter(s). You do not need a default constructor. · There are appropriate setter and getter methods for each member of the Class. · There is a toString method · There is an equals method // Person class not part of answer public class Person { String name; public Person( String name ) { this.name = name; } private String getName( ) { return name; } public void setName( String name ) {

public class Friend extends Person { private int birthDay; private static int friendCount = 0; public Friend(String name, int birthDay) { super(name); this.birthDay = birthDay; friendCount++; } public int getBirthDay() { return birthDay; } public void setBirthDay(int birthDay) { this.birthDay = birthDay; } publice int getFriendCount( ) { return friendCount; } public String toString() { return super.toString() + getClass().getName() + "@" + birthDay + ":" + friendCount; } public boolean equals(Object o) { if (!(o instanceof Friend)) { return false; } Friend f = (Friend) o; return super.equals(f) && birthDay == f.getBirthDay(); } }

Write a generic method that returns a new array that is a shallow copy of the array that is passed in as a parameter without using any predefined java clone or copy methods

public class GenericArray<T>{ public T[ ] shallowCopy(T [ ] source){ T[] copy; copy = (T[ ]) new Object[source.length]; for(int i = 0; i<source.length; i++){ copy[i] = source[i]; } return copy; } }

2. Write a complete and syntactically correct Java Class named Hourly that implements the following concepts of an hourly employee: - The Class is a subclass of the Employee Class - The Class keeps track of the employee's hourly pay rate as a double. - The Class has a single overload constructor that includes all of the necessary values to create a complete instance of the Class as parameter(s). You do not need a default constructor. - There are appropriate setter and getter methods for each member of the Class. - There is a toString method - There is an equals method

public class Hourly extends Employee { private double hourlyRate; public Hourly( String name, double hourlyRate ) { super( name ); this.hourlyRate = hourlyRate; } public void setHourlyRate( double hourlyRate ) { this.hourlyRate = hourlyRate; } public double gethourlyRate( ) { return hourlyRate; } public String toString( ) { return super.toString( ) + getClass( ).getName( ) + "@" + hourlyRate; } public boolean equals( Object o ) { if ( !( o instanceof Hourly ) ) return false; Hourly h = ( Hourly ) o; return super.equals( h ) && ( Math.abs( hourlyRate - h.hourlyRate ) < .01 ); } }

1. Write a complete Java class named Pet that has one instance variable, name, of type String. Include an overload constructor and all other "normally" expected methods. You do not need to include a default constructor.

public class Pet { private String name; public Pet( String name ) { this.name = name; } public void setName( String name ) { this.name = name; } public String getName( ) { return name; } public String toString( ) { return "name = " + name; } public boolean equals( Object o ) { if ( !( o instanceof Pet ) ) return false; Pet p = ( Pet ) o; return name.equals( p.name ); } }

1. Write a complete and syntactically correct Java Class named Player that implements the following concept of an player record: - The Class keeps track of the Players's name as a String - The Class has the ability to keep track of the total number of instances of the Class that have been instantiated. - The Class has a single overload constructor that includes all of the necessary values to create a complete instance of the Class as parameter(s). You do not need a default constructor. - There are appropriate setter and getter methods for each member of the Class. - There is a toString method - There is an equals method

public class Player { private String name; private static int playerCount = 0; public Player( String name ) { this.name = name; playerCount++; } public void setName( String name ) { this.name = name; } public String getName( ) { return name; } public int getPlayerCount( ) { return playerCount; } public String toString( ) { return getClass( ).getName( ) + "@playerCount = " + playerCount + ":name = " + name; } public boolean equals( Object o ) { if ( !( o instanceof Player ) ) return false; Player p = (Player) o; return name.equals( p.name ); } }

1. Write a complete and syntactically correct Java Class named Player that implements the following concept of an player record: - The Class keeps track of the Players's name as a String - The Class has the ability to keep track of the total number of instances of the Class that have been instantiated. - The Class has a single overload constructor that includes all of the necessary values to create a complete instance of the Class as parameter(s). You do not need a default constructor. - There are appropriate setter and getter methods for each member of the Class. - There is a toString method - There is an equals method

public class Player { private String name; private static int playerCount = 0; public Player( String name ) { this.name = name; playerCount++; } public void setName( String name ) { this.name = name; } public String getName( ) { return name; } public int getPlayerCount() { return playerCount; } public String toString() { return getClass().getName() + "@playerCount = " + playerCount + ":name = " + name; } public boolean equals( Object o ) { if ( !( o instanceof Player ) ) return false; Player p = (Player) o; return name.contains( p.name ); } }

Write a complete Java class named Snake that is a subclass of the Pet class and that has one instance variable, length, of type double. Include an overload constructor and all other "normally" expected methods. You do not need to include a default constructor.

public class Snake extends Pet { private double length; public Snake( String name, double length ) { super( name ); this.length = length; } public void setLength( int length ) { this.length = length; } public double getLength( ) { return length; } public String toString( ) { return super.toString() + ":" + length; } public boolean equals( Object o ) { if ( !( o instanceof Snake ) ) return false; Snake s = ( Snake ) o; return super.equals( s ) && ( Math.abs( length - s.length ) < .01 ); } }

1. Write a complete and syntactically correct Java class that is: a. a subclass of the Emp class defined in the previous question b. includes the following attributes: i. position as a char ii. pay as an double c. includes all of the "normally expected" methods

public class Worker extends Employee { public char position; public double pay; public Worker( ) { super( ); } public Worker( String name, int id, char position, double pay ) { super( name, id ); this.position = position; this.pay = pay; } public char getPosition( ) { return position; } public void setPosition( char newPosition ) { position = newPosition; } public double getPay( ) { return pay; } public void setPay( double newPay ) { pay = newPay; } public String toString( ){ return super.toString() + ":" + getClass( ).getName( ) + ":" + position + ":" + pay; } public boolean equals( Object o ) { if ( !( o instanceof Worker ) ) return false; Worker obj = ( Worker ) o; return super.equals( o ) && position == obj.position && ( pay - obj.pay < .01 ); } }

1. What are both the mathematically precise statement of the number of primitive operations and the Big-Oh for the running time of the following algorithm? public static int exam3(int[] arr){ int n = arr.length; int total = 0; for(int j = 0; j < n; j++;) for(int k = 0; k < n; k++) total += arr[j]; return total; }

public static int exam3( int[] arr ){ int n = arr.length; 1 int total = 0; 1 for ( int j = 0; j < n; j++ ) 1 2 for ( int k = 0; k < n; k++ ) 1 2 total += arr[j]; 3 return total; 1 } 4 + 3n + 5n^2

2. Write the complete and syntactically correct Java size( ) method for a generic SinglyLinkedList that returns the number of elements in list. Write this method: a. As a member of the SinglyLinkedList class. b. Assuming that we did not maintain size as an instance variable. The start of the generic SinglyLinkedList Class definition is: public class SinglyLinkedList<E> { private static class Node<E> { private E element; private Node<E> next; public Node(E e, Node<E> n) { element = e; next = n; } public E getElement() { return element; } public Node<E> getNext() { return next; } public void setNext(Node<E> n) { next = n; } } private Node<E> head = null; private Node<E> tail = null; // No additional instance variables.

public int size( ){ if ( head == null ) return 0; int count = 1; Node<E> temp = head; while ( temp.next != null ){ temp = temp.next; count++; } return count; }

1. Write a complete and syntactically correct Java interface for an Employee entity where: a. the Employee attributes are: i. name that is stored as a String ii. id that is stores as an int b. the interface supports all of the "normally expected" methods

public interface EmployeeInterface { String getName( ); void setName( String newName ); int getId( ); void setId( int newId ); @Override String toString( ); @Override boolean equals( Object o ); }

5. Write the complete and syntactically correct generic Java method named secondToLast( ) for the generic SinglyLinkedList class that returns (but does not remove) the element in the secondToLast node of the singlyLinkedList if that node exists and returns null if that node does not exist. The secondToLast node is defined as the node that is two nodes away from the last node in the list, i.e. Keep in mind that the method that you are writing is a member of the generic SinglyLinkededList class. For your reference, the start of the generic SinglyLinkedList Class definition is: public class SinglyLinkedList<E> { private static class Node<E> { private E element; private Node<E> next; public Node(E e, Node<E> n) { element = e; next = n; } public E getElement() { return element; } public Node<E> getNext() { return next; } public void setNext(Node<E> n) { next = n; } } private Node<E> head = null; private Node<E> tail = null; private int size = 0; // ... // you should know the other members/methods // of SinglyLinkedList class //

public secondToLast( ) { if ( size < 3 ) return null; Node temp = head; for (int i = 0; i < size - 3; i++ ) { temp = temp.getNext( ); } return temp.getElement( ); }

6. What are both the mathematically precise statement and the Big-Oh for the worst-case running time of the following method?

public static <K> void exam1( int data ) { n0 n1 n2 n3 n4 for (int i = 0; i < data.length; i++) { 1 2 for (int j = 0; j < data.length - 1; j++) { 1 2 if ( j[i] >= j[i+1] ) { 4 K temp = data[j]; 2 data[j] = data[j + 1]; 3 data[j + 1] = temp; 3 } } 1 3 14 } 14n2 + 3n + 1 O( n2 ) }

Write a method that will create a deep copy of an ArrayList of Integers

public static ArrayList<Integer> deepCopy(ArrayList<Integer> source){ ArrayList<Integer> copy = new ArrayList<>(source.size()); for(int i = 0; i<source.size(); i++){ int x = source.get(i); copy.add(x); } return copy; }

1. Write a boolean method named isInt that: a. Has the signature: boolean isInt( String inString ) b. Returns true if inString can represent an int. c. Returns false if inSting cannot represent an int. d. Does not depend on or use any other Java class or method except: i. The charAt( ) method from the String class ii. The length( ) method from the String class

public static boolean isInt2(String data) { // null String and String of length zero if (data == null || data.length() < 1) return false; // String of length 1, char must be a digit if (data.length() == 1 && isDigit(data.charAt(0))) return true; // String of length 1, char cannot be a sign if (data.length() == 1 && !isDigit(data.charAt(0))) return false; // String of length 2 or more if (!(isSign(data.charAt(0)) || isDigit(data.charAt(0)))) { return false; } for (int i = 1; i < data.length(); i++) { if (!isDigit(data.charAt(i))) { return false; } } // String must start with an optional sign followed by digits. return true; } public static boolean isDigit(char character) { return (character == '0' || character == '1' || character == '2' || character == '3' || character == '4' || character == '5' || character == '6' || character == '7' || character == '8' || character == '9'); } public static boolean isSign(char character) { return character == '+' || character == '-'; } // The easy method that depends on two unallowed Classes public static boolean isInt(String data) { String intString = data; try { Integer.parseInt(intString); return true; } catch (NumberFormatException nfe) { return false; }

5. What are both the mathematically precise statement and the Big-Oh for the worst case running time of the following algorithm?

public static double[] exam1(double[] x ) { n^0 n^1 n^2 int n = x.length; 1 double[] a = new double[n]; 1 for ( int j = 0; j < n; j++ ) 1 2 { double total = 0; 1 for ( int i = 0; i < j; i++ ) 1 2 total += x[i]; 3 a[j] = total / ( j + 1 ); 4 } return a; 1 } --- --- --- 4 8 5 4 + 8n + 5n2 BigO( n2 )

Ackerman's function is defined recursively for two nonnegative integers m and n as follows: n + 1 if m = 0 Ackerman( m, n ) = ackerman( m - 1, 1 ) if n = 0 ackerman( m - 1, ackerman ( m, n - 1 ) ) otherwise Write a recursive method to compute Ackerman's function. Your solution does NOT have to check for valid parmeters.

public static int ackerman( int m, int n ) { if ( m = = 0 ) return n + 1; else if ( n = = 0 ) return ackerman( m - 1, 1 ); else return ackerman( m -1, ackerman( m, n -1 )); }

1. What are both the mathematically precise statement and the Big-Oh for the worst case running time of the following algorithm? // assume equal length arrays // Version A public static int exam1( int[ ] first, int[ ] second, int[ ] third, int[ ] fourth )

public static int exam1( int[ ] first, int[ ] second, int[ ] third, int[ ] fourth ) { n^0 n^1 n^2 n^3 n^4 int n = first.length; 1 int total = 0; 1 for ( int i = 0; i < n; i++ ) 1 2 { total += first[ i ]; 3 } for ( int j = 0; j < n; j++ ) 1 2 { total += second[ j ]; 3 } for ( int k = 0; k < n; k++ ) 1 2 { total += third[ k ]; 3 } for ( int l = 0; l < n; l++ ) 1 2 { total += fourth[ l ]; 3 } return total; 1 } 7 20 20n + 7 O( n )

2. What are both the mathematically precise statement and the Big-Oh for the worst case running time of the following algorithm?

public static int exam1( int[ ] x ) { int y = x.length; 1 int a = x [ 0 ]; 2 for ( int i = 1; i < y; i++ ) 1 to initialize i loop (n-1) times 1 for comparison { if ( x[ i ] > y ) 2 a = x[ i ]; 2 1 for i++ } return y; 1 } Worst case: 1 + 2 + 1 + ( n - 1 ) * 6 + 1 5 + 6n - 6 6n - 1 O( n ) Best, if always false: 1 + 2 + 1 + ( n - 1 ) * 4 + 1 5 + 4n - 6 5n - 1 O(n)

1. What are both the mathematically precise statement and the Big-Oh for the worst-case running time of the following algorithm?

public static int exam1(int[][][] data) { x^0 x^1 x^2 x^3 int a, b, c, m, q, t, x, z; a = b = c = m = q = t = x = z = 0; 8 for (c = 0; c < data.length; c++) { 1 2 for (m = 0; m < data[c].length; m++) { 1 2 for (z = 0; z < data[c][m].length; z++) { 1 2 b += data[c][m][z]; 4 } } } for (t = 0; t < data.length; t++) { 1 2 data[0][0][0] = data[t][0][0]; 3 for (x = 0; x < data[t].length; x++); 1 2 for (q = 0; q < data[t][x].length; q++) { 1 2 data[t][x][q] = b; 1 } } return b; 1 } 11 9 6 9 9 n^3 + 6 n^2 + 9 n + 11 O( n^3 )

5. Euclid devised a clever algorithm for computing the greatest common divisior of two integers. According to Euclid's algorithm, gcd( n, m ) if n > m gcd( m, n ) = m if n = 0 gcd( n, m mod n ) if n > 0 note: mod is the modulus operator, in Java m mod n is written as m % n Write a recursive method to compute greatest common divisors via Euclid's method. Your solution does NOT have to check for valid parmeters. Note: in Java m mod n is written as m % n

public static int gcd( int m, int n ){ if ( n > m ) return gcd(n, m); if ( n = = 0) return m; if ( n > 0 ) return gcd( n, ( m % n ) ); return -1; // should never be reached. // but necessary for compiler }

Euclid devised a clever algorithm for computing the greatest common divisior of two integers. According to Euclid's algorithm, gcd( n, m ) if n > m gcd( m, n ) = m if n = 0 gcd( n, m mod n ) if n > 0 Write a recursive method to compute greatest common divisors via Euclid's method. Your solution does NOT have to check for valid parmeters.

public static int gcd( int m, int n ){ if ( n > m ) return gcd(n, m); if ( n = = 0) return m; if ( n > 0 ) return gcd( n, ( m % n ) ); return -1; // should never be reached. // but necessary for compiler }

1. Euclid devised a clever algorithm for computing the greatest common divisor of two integers. According to Euclid's algorithm, gcd( n, m ) if n > m gcd( m, n ) = m if n = 0 gcd( n, m mod n ) if n > 0 note: mod is the modulus operator, in Java m mod n is written as m % n Write a complete and syntactically correct recursive method to compute greatest common divisors using Euclid's method. Your solution does NOT have to check for valid parameters. Note: in Java m mod n is written as m % n

public static int gcd( int m, int n ){ if ( n > m ) return gcd(n, m); // reverse parameters if needed if ( n = = 0) return m; if ( n > 0 ) return gcd( n, ( m % n ) ); return -1; // should never be reached. // but necessary for compiler }

1. Write a complete and syntactically correct recursive Java method to compute: · the kth power of 2 where k is a natural number · a natural number is a positive whole number including zero · 20 = 1 · your solution must check for valid parameters

public static int powerOfTwo( int n ) throws InvalidParameterException { // parameter checks if ( n < 0 ) throw new InvalidParameterException( "parameter must be zero or greater" ); if ( n > 30 ) throw new InvalidParameterException( "parameter must be less than 31" ); // base case if ( n == 0 ) return 1; // general case return 2 * powerOfTwo( n - 1 ); }

1. The sum of positive integers between 1 and n inclusively can be express mathematically as: Write a complete and syntactically correct recursive Java method to compute the sum of all numbers between 1 to N inclusive. Make sure that your solution correctly handles all possible parameter values.

public static int sum ( int i ) { if ( i < 1 ) throw new IllegalArgumentException( "sum only works for positive integers ); if ( i == 1 ) return 1; return i + sum( i - 1 ); }

5. Write a recursive method that: a. returns the sum of the even integers between 0 and n b. throws an appropriate exception if passed an invalid parameter

public static int sum( int n ) { if ( n < 0 ) throw new IllegalArgumentException( "n must be >= 0" ); if ( n == 0 ) // base case return 0; if ( n % 2 == 0 ) // general cases return n + sum( n - 1 ); // add even values else return sum( n - 1 ); // don't add odd values }

1. The sum of positive integers between 1 and n inclusively can be express mathematically as: Write a complete and syntactically correct recursive Java method to compute the sum of all numbers between 1 to N inclusive. Make sure that your solution correctly handles all possible parameter values.

public static int sum( int n ) { if ( n < 1 ) throw new IllegalParameterException( "n must be >= 1 " ); if ( n == 1 ) return 1; return n + sum( n - 1 ); }

1. What are both the mathematically precise statement and the Big-Oh for the worst-case running time of the following algorithm?

public static void exam1(int[ ][ ] data) n^0 n^1 n^2 { System.out.println(" The Stuff "); 1 for (int j = 0; j < data[0].length; j++) { 2 2 System.out.print("------"); 1 } for (int i = 0; i < data.length; i++) { 2 1 System.out.println(); 1 for (int k = 0; k < data[i].length; k++) { 2 2 System.out.print(" "); 1 System.out.print(data[i][k]); 3 System.out.print(" "); 1 } System.out.println(""); 1 for (int l = 0; l < data[i].length; l++) { 2 2 System.out.print("------"); 1 } System.out.println(""); 1 } System.out.println(" No More Stuff "); 1 } 6 11 10 10 n^2 + 11 n + 6 O( n^2 )

1. Write a complete and syntactically correct Java add method for the generic ArrayBag Class. Remember that the add method doubles the size of the bag when the array is full. The following lines of code define the members of the ArrayBag class: public class ArrayBag <T> implements Bag <T> { private T[] bag; // the array of objects private int count; // number of object in the array

public void add( T element ) { if ( count == bag.length ) { T[ ] temp = ( T[ ] ) new Object[ bag.length * 2 ]; for ( int i = 0; i < count; i++ ) temp[ i ] = bag[ i ]; bag = temp; } bag[ count ] = element; count++; }

1. Write a complete and syntactically correct Java add method for the generic ArrayBag Class. Remember that the add method doubles the size of the bag when the array is full. The following lines of code define the members of the ArrayBag class: public class ArrayBag <T> implements Bag <T> { private T[] bag; // the array of objects private int count; // number of object in the array

public void add( T element ) { if ( count == bag.length ) { T[ ] temp = ( T[ ] ) new Object[ bag.length * 2 ]; for ( int i = 0; i < count; i++ ) temp[ i ] = bag[ i ]; bag = temp; } bag[ count ] = element; count++; }

1. Write the complete, syntactically correct, generic Java code for the addFirst( E e ) method for the DoublyLinkedList class as defined in the textbook. The start of the DoublyLinkedList class is given below. If your answer includes any methods defined in the DoublyLinkedList class that are not given below then you must provide the code for those methods as well. public class DoublyLinkedList<E> { private static class Node<E> { private E element; private Node<E> prev; private Node<E> next; public Node(E e, Node<E> p, Node<E> n) { element = e; prev = p; next = n; } public E getElement() { return element; } public Node<E> getPrev() { return prev; } public Node<E> getNext() { return next; } public void setPrev(Node<E> p) { prev = p; } public void setNext(Node<E> n) { next = n; } } private Node<E> header; // header sentinel private Node<E> trailer; // trailer sentinel private int size = 0; ...

public void addFirst( E e ){ Node<E> newest = newNode<>( e, null, null ); newNode.setNext( header.getNext( ) ); header.setNext( newNode ); newNode.setPrev( header); size++; }

public void addFirst(E e) { addBetween(e, header, header.getNext()); // place just after the header }

public void addFirst2(E e) { Node<E> newNode = new Node<>( e, null, null ); newNode.setNext( header.getNext( ) ); newNode.setPrev( header ); header.getNext.setPrev( newNode ); header.setNext( newNode ); size++; }

Write a method named addLast to insert an element at the end of a generic SinglyLinked List assuming that the start of the generic SinglyLinked List class definition is: public class SinglyLinkedList<E> { private static class Node<E> { private E element; private Node<E> next; public Node(E e, Node<E> n) { element = e; next = n; } public E getElement() { return element; } public Node<E> getNext() { return next; } public void setNext(Node<E> n) { next = n; } } private Node<E> head = null; private Node<E> tail = null; private int size = 0;

public void addLast(E e) { // adds element e to the end of the list Node<E> newest = new Node<>(e, null); // node will eventually be the tail if (isEmpty()) head = newest; // special case: previously empty list else tail.setNext(newest); // new node after existing tail tail = newest; // new node becomes the tail size++; }

Write a method named trim for the ArrayBag class that shrinks the size of the bag array so that its length is equal to the number of objects currently in the bag array. Assume that the start of the ArrayBag class definition is: public class ArrayBag <T> implements Bag <T> { private T[ ] bag; // the array of objects private int count; // number of object in the array

public void trim( ) { T[ ] temp = ( T[ ] ) new Object[ bag.count ]; for ( int i = 0; i < temp.count; i++ ) temp[ i ] = bag[ i ]; bag = temp; }

1. Write a complete and syntactically correct Java trim method for the generic ArrayBag Class. The method should reduce the size of the array so that matches the number of elements in the bag with no "left over" empty array slots. If your trim method class any other methods you must write the code for those methods as well. The following lines of code define the members of the ArrayBag class: public class ArrayBag <T> implements Bag <T> { private T[] bag; // the array of objects private int count; // number of object in the array

public void trim( ) { T[ ] temp = ( T[ ] ) new Object[ count ]; for ( int i = 0; i < count; i++ ) temp[ i ] = bag[ i ]; bag = temp; }

2. Write a complete and syntactically correct Java trim method for the generic ArrayBag Class. The method should reduce the size of the array so that matches the number of elements in the bag with no "left over" empty array slots. The following lines of code define the members of the ArrayBag class: public class ArrayBag <T> implements Bag <T> { private T[] bag; // the array of objects private int count; // number of object in the array

public void trim( ) { T[ ] temp = ( T[ ] ) new Object[ count ]; for ( int i = 0; i < count; i++ ) temp[ i ] = bag[ i ]; bag = temp; }

2. Write a complete and syntactically correct Java trim method for the generic ArrayBag Class. The method should reduce the size of the array so that matches the number of elements in the bag with no "left over" empty array slots. The following lines of code define the members of the ArrayBag class: public class ArrayBag <T> implements Bag <T> { private T[] bag; // the array of objects private int count; // number of objects in the array

public void trim( ) { T[ ] temp = ( T[ ] ) new Object[ count ]; for ( int i = 0; i < count; i++ ) temp[ i ] = bag[ i ]; bag = temp; }

1. Write a complete and syntactically correct Java trim method for the generic ArrayBag Class. The method should reduce the size of the array so that matches the number of elements in the bag with no "left over" empty array slots. The following lines of code define the members of the ArrayBag class: public class ArrayBag <T> implements Bag <T> { private T[] bag; // the array of objects private int count; // number of object in the array

public void trim( ) { if ( count < bag.length ) { int newSize = count; if (count < 2 ) newSize = 1; T[ ] temp = ( T[ ] ) new Object[ newSize ]; for ( int i = 0; i < count; i++ ) temp[ i ] = bag[ i ]; bag = temp; } }

1. Write the complete, syntactically correct, generic Java removeLast( ) method for a SinglyLinkedList. Write this method: a. As a member of the SinglyLinkedList class. b. So that it returns the element that is in the node being removed from the list. The start of the generic SinglyLinkedList Class definition is: public class SinglyLinkedList<E> { private static class Node<E> { private E element; private Node<E> next; public Node(E e, Node<E> n) { element = e; next = n; } public E getElement() { return element; } public Node<E> getNext() { return next; } public void setNext(Node<E> n) { next = n; } } private Node<E> head = null; private Node<E> tail = null; private int size = 0;

removeLast( ) { if ( size == 0 ) return null; else if ( size == 1 ) { E tempElement = head.getElement( ); head = null; tail == null; size = 0; return tempElement; } else { Node<E> temp = head; while ( temp.next.next != null ) temp = temp.next; E tempElement = temp.next.getElement( ); temp.next = null; tail = temp; size--; return tempElement; }

We have discussed three levels of equivalence in class. Given two arrays of generic objects define each level of equivalence. Use diagrams to illustrate your answers when appropriate. Also write a Java method named eLevel that that takes two generic array references as parameters and returns an integer value that indicates their level of equivalence. You may determine what integer value indicates what level of equivalence.

· Level 1 - array references point to same array in memory · Level 2 - arrary references point to differnet arrays in memory but the object pointers in the arrays point the the same objects in memory · Level 3 - array references point to different arrays in memory and the object points point to different object instances but the different instances are equal to each other. // code assumes in-order arrays. public static int eLevel <E> <T> ( E[ ] array1, T[ ] array 2 ) { if ( !( array1 instanceof array2 ) ) return 0; else if ( array1 = = array2 ) // same array return 1; else int equal2 = 2; for ( int i = 0; i < array1.length; i++ ) if ( array1[i] != array2[i] ) // shallow equals = 0; if ( equal2 == 2 ) return equal2; else int equal3 = 3; for ( int i = 0; i < array1.length; i++ ) if( !array1[i].equals( array2[i] ) // deep equal3 = 0; if ( equal3 == 0 ) return 0; else return equal3; }


Conjuntos de estudio relacionados

Almost, Maine - Daniel (Man) and Hope

View Set

Communities Develop and Montana Becomes a Territory

View Set

A&P Ch. 12: Membrane Potential and the Action Potential

View Set

chapter 1: dynamic environment of hrm

View Set

Penn Foster, Computer Applications

View Set

Introduction to Business & Entrepreneurship - Module 9 Quiz

View Set

Train & Development - Chapter 5 - Learning & Transfer of Training

View Set