Study Guide ch 7 for comp sci

Pataasin ang iyong marka sa homework at exams ngayon gamit ang Quizwiz!

Consider the following code segment from an insertion sort program. for(int j = 1; j < arr.length; j++) { int insertItem = arr[j]; int k = j - 1; while (k >= 0 && insertItem < arr[k]) { arr[k + 1] = arr[k]; k--; } arr[k + 1] = insertItem; } Assume that array arr has been defined and initialized with the values {5, 4, 3, 2, 1}. What are the values in array arr after two passes of the for loop (i.e., when j = 2 at the point indicated by / * end of for loop * / ) ?

{3, 4, 5, 2, 1}

Consider the following method. public static void sort(String[] arr) { for (int pass = arr.length - 1; pass >= 1; pass--) { String large = arr[0]; int index = 0; for (int k = 0; k <= pass; k++) { if ((arr[k].compareTo(large)) > 0) { large = arr[k]; index = k; } } arr[index] = arr[pass]; arr[pass] = large; } } Assume arr is the following array. What is the intermediate value of arr after two iterations of the outer for loop in the call sort(arr)?

"Ann" "Mike" "Walt" "Lisa" "Shari" "Jose" "Mary" "Bill"

Assume that myList is an ArrayList that has been correctly constructed and populated with objects. Which of the following expressions produces a valid random index for myList?

(int) ( Math.random () * myList.size () )

Consider the following instance variable and method. Method wordsWithCommas is intended to return a string containing all the words in listOfWords separated by commas and enclosed in braces.For example, if listOfWords contains ["one", "two", "three"], the string returned by the call wordsWithCommas () should be "{one, two, three}". Which of the following can be used to replace /* expression */ and /* condition */ so thatwordsWithCommas will work as intended?

/ * expression * / / / * condition * / listOfWords.size() / k != sizeOfList - 1

In the code segment below, assume that the ArrayList object numbers has been properly declared and initialized to contain [0, 2, 4, 5]. for (int k = numbers.size() - 1; k >= 0; k--) { if (numbers.get(k) > k) { System.out.print(k + " "); } } What, if anything, is printed as a result of executing the code segment?

3 2 1

In the following code segment, assume that the ArrayList data has been initialized to contain the Integer values [4, 3, 4, 5, 3, 4]. int j = 0; while (j < data.size() - 1) { if (data.get(j) > data.get(j + 1)) { System.out.print(data.get(j + 1) + " "); } j++; } What, if anything, is printed as a result of executing the code segment?

3 3

Consider the following correct implementation of the selection sort algorithm. public static void selectionSort(int[] elements) { for (int j = 0; j < elements.length - 1; j++) { int minIndex = j; for (int k = j + 1; k < elements.length; k++) { if (elements[k] < elements[minIndex]) { minIndex = k; // Line 11 } } if (j != minIndex) { int temp = elements[j]; elements[j] = elements[minIndex]; elements[minIndex] = temp; } } } The following declaration and method call appear in the same class as selectionSort. int[] vals = {5, 10, 2, 1, 12}; selectionSort(vals); How many times is the statement minIndex = k; in line 11 of the method executed as a result of the call to selectionSort ?

4

In the following code segment, assume that the ArrayList numList has been properly declared and initialized to contain the Integer values [1, 2, 2, 3]. The code segment is intended to insert the Integer value val in numList so that numList will remain in ascending order. The code segment does not work as intended in all cases. int index = 0; while (val > numList.get(index)) { index++; } numList.add(index, val); For which of the following values of val will the code segment not work as intended?

4

In the following code segment, assume that the ArrayList wordList has been initialized to contain the String values ["apple", "banana", "coconut", "lemon", "orange", "pear"]. int count = 0; for (String word : wordList) { if (word.indexOf("a") >= 0) { count++; } } System.out.println(count); What is printed as a result of executing the code segment?

4

Consider the following method, inCommon, which takes two Integer ArrayList parameters. The method returns true if the same integer value appears in both lists at least one time, and false otherwise. public static boolean inCommon(ArrayList<Integer> a, ArrayList<Integer> b) { for (int i = 0; i < a.size(); i++) { for (int j = 0; j < b.size(); j++) // Line 5 { if (a.get(i).equals(b.get(j))) { return true; } } } return false; } Which of the following best explains the impact to the inCommon method when line 5 is replaced by for (int j = b.size() - 1; j > 0; j--) ?

After the change, the method will never check the first element in list b.

Consider the following code segment. List<String> students = new ArrayList<String>(); students.add("Alex"); students.add("Bob"); students.add("Carl"); for(int k = 0; k < students.size(); k++) { System.out.print(students.set(k, "Alex") + " "); } System.out.println(); for(String str : students) { System.out.print(str + " "); } What is printed as a result of executing the code segment?

Alex Bob Carl Alex Alex Alex

Which of the following is a reason to use an ArrayList instead of an array?

An ArrayList resizes itself as necessary when items are added, but an array does not.

Consider the following code segment. ArrayList<Integer> oldList = new ArrayList(); oldList.add(100); oldList.add(200); oldList.add(300); oldList.add(400); ArrayList<Integer> newList = new ArrayList(); newList.add(oldList.remove(1)); newList.add(oldList.get(2)); System.out.println(newList); What, if anything, is printed as a result of executing the code segment?

[200, 400]

Consider the following method countNegatives, which searches an ArrayList of Integer objects and returns the number of elements in the list that are less than 0. public static int countNegatives(ArrayList<Integer> arr) { int count = 0; for (int j = 0; j < arr.size(); j++) // Line 4 { if (arr.get(j) < 0) { count++; } } return count; } Which of the following best explains the impact to the countNegatives method when, in line 4, j < arr.size() is replaced with j <= arr.size() - 1 ?

It has no impact on the behavior of the method.

Consider the following method findValue, which takes an ArrayList of String elements and a String value as parameters and returns true if the String value is found in the list and false otherwise. public static boolean findValue(ArrayList<String> arr, String key) { for (int j = 0; j < arr.size(); j++) // Line 3 { if (arr.get(j).equals(key)) { return true; } } return false; } Which of the following best explains the impact to the findValue method when, in line 3, int j = 0 is replaced by int j = 1 ?

It will cause the method to return a different result when the key value is found only at the first index in the list.

Consider the following method, which is intended to return a list containing the elements of the parameter myList with all even elements removed. public static ArrayList<Integer> removeEvens(ArrayList<Integer> myList) { for (int i = 0; i < myList.size(); i++) { if (myList.get(i) % 2 == 0) { myList.remove(i); } } return myList; } Which of the following best explains why the code segment does not work as intended?

The code segment returns a list with fewer elements than intended because it fails to consider the last element of myList.

The following method is intended to remove all elements of an ArrayList of integers that are divisible by key and add the removed elements to a new ArrayList, which the method returns. public static ArrayList<Integer> match(ArrayList<Integer> numList, int key) { ArrayList<Integer> returnList = new ArrayList<Integer>(); int i = 0; while (i < numList.size()) { int num = numList.get(i); if (num % key == 0) { numList.remove(i); returnList.add(num); } i++; } return returnList; } As an example, if the method is called with an ArrayList containing the values [5, 2, 10, 20, 16] and the parameter key has the value 5, then numList should contain [2, 16] at the end of the method and an ArrayList containing [5, 10, 20] should be returned. Which of the following best explains why the method does not always work as intended?

The method skips some elements of numList during the traversal.

The removeElement method is intended to remove all instances of target from the ArrayList object data passed as a parameter. The method does not work as intended for all inputs. public void removeElement(ArrayList<Integer> data, int target) { for (int j = 0; j < data.size(); j++) { if (data.get(j).equals(target)) { data.remove(j); } } } Assume that the ArrayList object scores and the int variable low_score have been properly declared and initialized. In which of the following cases will the method call removeElement(scores, low_score) fail to produce the intended result?

When scores is [8, 8, 4, 3, 3, 6] and low_score is 3

Consider the following instance variable and method. private List<String> animals; public void manipulate() { for(int k = animals.size() - 1; k > 0; k--) { if(animals.get(k).substring(0, 1).equals("b")) { animals.add(animals.size() - k, animals.remove(k)); } } } Assume that animals has been instantiated and initialized with the following contents. ["bear", "zebra", "bass", "cat", "koala", "baboon"] What will the contents of animals be as a result of calling manipulate?

["bear", "zebra", "bass", "cat", "koala", "baboon"]

Consider the following code segment. ArrayList<String> numbers = new ArrayList<String>(); numbers.add("one"); numbers.add("two"); numbers.add(0, "three"); numbers.set(2, "four"); numbers.add("five"); numbers.remove(1); Which of the following represents the contents of numbers after the code segment has been executed?

["three", "four", "five"]

Consider the following method. public static void mystery(List<Integer> nums) { for (int k = 0; k < nums.size(); k++) { if (nums.get(k).intValue() == 0) { nums.remove(k); } } } Assume that a List<Integer> values initially contains the following Integer values. [0, 0, 4, 2, 5, 0, 3, 0] What will values contain as a result of executing mystery(values) ?

[0, 4, 2, 5, 3]

Consider the following code segment. ArrayList<Integer> nums = new ArrayList<Integer>(); nums.add(new Integer(37)); nums.add(new Integer(3)); nums.add(new Integer(0)); nums.add(1, new Integer(2)); nums.set(0, new Integer(1)); nums.remove(2); System.out.println(nums); What is printed as a result of executing the code segment?

[1, 2, 0]

Consider the following correct implementation of the insertion sort algorithm. The insertionSort method correctly sorts the elements of ArrayList data into increasing order. public static void insertionSort(ArrayList<Integer> data) { for (int j = 1; j < data.size(); j++) { int v = data.get(j); int k = j; while (k > 0 && v < data.get(k - 1)) { data.set(k, data.get(k - 1)); /* Statement 1 */ k--; } data.set(k, v); /* Statement 2 */ /* End of outer loop */ } } Question Assume that insertionSort has been called with an ArrayList parameter that has been initialized with the following Integer objects. [5, 2, 4, 1, 3, 6] What will the contents of data be after three passes of the outside loop (i.e., when j == 3 at the point indicated by /* End of outer loop */) ?

[1, 2, 4, 5, 3, 6]

Consider the following method public ArrayList<Integer> mystery(int n) { ArrayList<Integer> seq = new ArrayList<Integer>(); for (int k = 1; k <= n; k++) seq.add(new Integer(k * k + 3)); return seq; } Which of the following is printed as a result of executing the following statement?

[4, 7, 12, 19, 28, 39]

Consider the following data field and method. private ArrayList list; public void mystery(int n) { for (int k = 0; k < n; k++) { Object obj = list.remove(0); list.add(obj); } } Assume that list has been initialized with the following Integer objects. [12, 9, 7, 8, 4, 3, 6, 11, 1] Which of the following represents the list as a result of a call to mystery(3)?

[8, 4, 3, 6, 11, 1, 12, 9, 7]

Consider the following code segment. ArrayList<Double> conditionRating = new ArrayList<Double>(); conditionRating.add(9.84); conditionRating.add(8.93); conditionRating.add(7.65); conditionRating.add(6.24); conditionRating.remove(2); conditionRating.set(2, 7.63); System.out.println(conditionRating); What is printed when this code segment is executed?

[9.84, 8.93, 7.63]

Consider the following code segment. ArrayList<String> items = new ArrayList<String>(); items.add("A"); items.add("B"); items.add("C"); items.add(0, "D"); items.remove(3); items.add(0, "E"); System.out.println(items); What is printed as a result of executing the code segment?

[E, D, A, B]

Consider the following code segment. List<String> animals = new ArrayList<String>(); animals.add("dog"); animals.add("cat"); animals.add("snake"); animals.set(2, "lizard"); animals.add(1, "fish"); animals.remove(3); System.out.println(animals); What is printed as a result of executing the code segment?

[dog, fish, cat]

Consider the following code segment. ArrayList<String> animals = new ArrayList<>(); animals.add("fox"); animals.add(0, "squirrel"); animals.add("deer"); animals.set(2, "groundhog"); animals.add(1, "mouse"); System.out.println(animals.get(2) + " and " + animals.get(3)); What is printed as a result of executing the code segment?

fox and groundhog

Consider the following class declaration. public class StudentInfo { private String major; private int age; public String getMajor() public int getAge() } The following instance variable and method appear in another class. private List<StudentInfo> students; public double averageAgeInMajor(String theMajor) { double sum = 0.0; int count = 0; for (StudentInfo k : students) { } if (count > 0) { return sum / count; } else { return - 1.0; } } Which of the following could be used to replace /* missing code */ so that averageAgeInMajor will compile without error? Responses

to be edited

Consider the following class definition. public class Value { private int num; public int getNum() { return num; } // There may be instance variables, constructors, and methods not shown. } The following method appears in a class other than Value. It is intended to sum all the num instance variables of the Value objects in its ArrayList parameter. /** Precondition: valueList is not null */ public static int getTotal(ArrayList<Value> valueList) { int total = 0; /* missing code */ return total; } Which of the following code segments can replace /* missing code */ so the getTotal method works as intended?

i and ii for (int x = 0; x < valueList.size(); x++) { total += valueList.get(x).getNum(); } for (Value v: valueList) { total += v.getNum(); }

The following sort method correctly sorts the integers in elements into ascending order Which of the following changes to the sort method would correctly sort the integers in elements into descending order?

i and iii only replace line 9 with replace line 3 and 7 with

Consider the following declaration of the class NumSequence, which has a constructor that is intended to initialize the instance variable seq to an ArrayList of numberOfValues random floating-point values in the range [0.0, 1.0). public class NumSequence { private ArrayList<Double> seq; // precondition: numberOfValues > 0 // postcondition: seq has been initialized to an ArrayList of // length numberOfValues; each element of seq // contains a random Double in the range [0.0, 1.0) public NumSequence(int numberOfValues) { /* missing code */ } } Which of the following code segments could be used to replace /* missing code */ so that the constructor will work as intended?

ii and iii seq = new ArrayList<Double>(); for(int k = 0; k < numberOfValues; k++) seq.add(new Double(Math.random())); ArrayList<Double> temp = new ArrayList<Double>(); for (int k = 0; k < numberOfValues; k++) temp.add(new Double(Math.random())); seq = temp;

The following incomplete method is intended to sort its array parameter arr in increasing order. // postcondition: arr is sorted in increasing order public static void sortArray(int[] arr) { int j, k; for (j = arr.length - 1; j > 0; j--) { int pos = j; for ( /* missing code */ ) { if (arr[k] > arr[pos]) { pos = k; } } swap(arr, j, pos); } } Assume that swap(arr, j, pos) exchanges the values of arr[j] and arr[pos]. Which of the following could be used to replace /* missing code */ so that executing the code segment sorts the values in array arr?

k = j - 1; k >= 0; k--

Consider the following method that is intended to modify its parameter nameList by replacing all occurrences of name with newValue. public void replace(ArrayList<String> nameList, String name, String newValue) { for (int j = 0; j < nameList.size(); j++) { if ( /* expression */ ) { nameList.set(j, newValue); } } } Which of the following can be used to replace /* expression */ so that replace will work as intended?

nameList.get(j).equals(name)

Consider the following code segment. ArrayList<String> colors = new ArrayList<String>(); colors.add("Red"); colors.add("Orange"); colors.set(1, "Yellow"); colors.add(1, "Green"); colors.set(colors.size() - 1, "Blue"); colors.remove(0); System.out.println(colors); What is printed as a result of executing the code segment?

to be edited

The following questions refer to the code in the GridWorld case study. A copy of the code is provided below. Consider the design of a Grasshopper class that extends Bug. When asked to move, a Grasshopper moves to a randomly chosen empty adjacent location that is within the grid. If there is no empty adjacent location that is within the grid, the Grasshopper does not move, but turns 45 degrees to the right without changing its location. Appendix B — Testable API info.gridworld.grid.Location class (implements Comparable)

to be edited

Consider the following code segment. ArrayList<Integer> numList = new ArrayList<Integer>(); numList.add(3); numList.add(2); numList.add(1); numList.add(1, 0); numList.set(0, 2); System.out.print(numList); What is printed by the code segment?

[2, 0, 2, 1]

Consider the following correct implementation of the insertion sort algorithm. public static void insertionSort(int[] elements) { for (int j = 1; j < elements.length; j++) { int temp = elements[j]; int possibleIndex = j; while (possibleIndex > 0 && temp < elements[possibleIndex - 1]) { elements[possibleIndex] = elements[possibleIndex - 1]; possibleIndex--; // Line 10 } elements[possibleIndex] = temp; } } The following declaration and method call appear in a method in the same class as insertionSort. int[] arr = {4, 12, 4, 7, 19, 6}; insertionSort(arr); How many times is the statement possibleIndex--; in line 10 of the method executed as a result of the call to insertionSort ?

to be edited

Consider the following correct implementation of the insertion sort algorithm. The insertionSort method correctly sorts the elements of ArrayList data into increasing order. public static void insertionSort(ArrayList<Integer> data) { for (int j = 1; j < data.size(); j++) { int v = data.get(j); int k = j; while (k > 0 && v < data.get(k - 1)) { data.set(k, data.get(k - 1)); /* Statement 1 */ k--; } data.set(k, v); /* Statement 2 */ /* End of outer loop */ } } Question Assume that insertionSort is called with an ArrayList parameter that has been initialized with the following Integer objects. [1, 2, 3, 4, 5, 6] How many times will the statements indicated by /* Statement 1 */ and /* Statement 2 */ execute?

to be edited

Consider the following correct implementation of the selection sort algorithm. public static void selectionSort(int[] elements) { for (int j = 0; j < elements.length - 1; j++) { int minIndex = j; for (int k = j + 1; k < elements.length; k++) { if (elements[k] < elements[minIndex]) { minIndex = k; } } if (j != minIndex) { int temp = elements[j]; elements[j] = elements[minIndex]; elements[minIndex] = temp; // Line 19 } } } The following declaration and method call appear in a method in the same class as selectionSort. int[] arr = {9, 8, 7, 6, 5}; selectionSort(arr); How many times is the statement elements[minIndex] = temp; in line 19 of the method executed as a result of the call to selectionSort ?

to be edited

Consider the following interface and class declarations. public interface Vehicle { double getMileage(); } public class Fleet { private ArrayList<Vehicle> myVehicles; public double getTotalMileage() { double sum = 0.0; for (Vehicle v : myVehicles) { sum += /* expression */; } return sum; } } Which of the following can be used to replace /* expression */ so that getTotalMileage returns the total of the miles traveled for all vehicles in the fleet?

to be edited

Consider the following method. /** Removes all occurrences of nameToRemove from nameList. * @param nameList a list of names * @param nameToRemove a name to be removed from nameList */ public void removeName(List<String> nameList, String nameToRemove) { /* missing implementation */ } Which of the following can be used to replace /* missing implementation */ so that removeName will work as intended?

to be edited

Consider the following statement, which is intended to create an ArrayList named theater_club to store elements of type Student. Assume that the Student class has been properly defined and includes a no-parameter constructor. ArrayList<Student> theater_club = new /* missing code */; Which choice can replace /* missing code */ so that the statement compiles without error?

to be edited

Consider the following statement, which is intended to create an ArrayList named values that can be used to store Integer elements. /* missing code */ = new ArrayList<>(); Which of the following can be used to replace /* missing code */ so that the statement compiles without error? 1. ArrayList values 2. ArrayList<int> values 3. ArrayList<Integer> values

to be edited

Consider the following statement, which is intended to create an ArrayList named years that can be used to store elements both of type Integer and of type String. /* missing code */ = new ArrayList(); Which of the following can be used to replace /* missing code */ so that the statement compiles without error?

to be edited

Consider the following two data structures for storing several million words. I. An array of words, not in any particular order II. An array of words, sorted in alphabetical order Which of the following statements most accurately describes the time needed for operations on these data structures?

to be edited

Consider the static method selectSort shown below. Method selectSort is intended to sort an array into increasing order; however, it does not always work as intended. // precondition: numbers.length > 0 // postcondition: numbers is sorted in increasing order public static void selectSort(int[] numbers) { int temp; Line 1: for (int j = 0; j < numbers.length - 1; j++) { Line 2: int pos = 0; Line 3: for (int k = j + 1; k < numbers.length; k++) { Line 4: if (numbers[k] < numbers[pos]) { Line 5: pos = k; } } temp = numbers[j]; numbers[j] = numbers[pos]; numbers[pos] = temp; } } Which of the following changes should be made so that selectSort will work as intended?

to be edited

Directions: Select the choice that best fits each statement. The following question(s) refer to the following information. Consider the following sort method. This method correctly sorts the elements of array data into increasing order. public static void sort(int [] data) { for (int j = 0; j < data.length - 1; j++) { int m = j; for (int k = j + 1; k < data.length; k++) { if (data[k] < data[m]) { m = k; } } int temp = data[m]; data[m] = data[j]; data[j] = temp; } } Assume that sort is called with the array {1, 2, 3, 4, 5, 6}. How many times will the expression indicated by /* Compare values */ and the statement indicated by /* Assign to temp */ execute?

to be edited

The following question refer to the following information. Consider the following data field and method. The method removeDups is intended to remove all adjacent duplicate numbers from myData, but does not work as intended. private ArrayList myData; public void removeDups () { int k = 1; while (k < myData.size()) { if (myData.get(k).equals(myData.get(k - 1))) { myData.remove(k); } k++; } } For example, if myData has the values 3 3 4 4 4 8 7 7 7, after calling removeDups, myData should have the values 3 4 8 7. Assume that myData has the following values. 2 7 5 5 5 5 6 6 3 3 3 Which of the following representsmyDataafter the incorrectremoveDupsis executed?

to be edited

The following question refer to the following information. Consider the following data field and method. The method removeDups is intended to remove all adjacent duplicate numbers from myData, but does not work as intended. private ArrayList myData; public void removeDups () { int k = 1; while (k < myData.size()) { if (myData.get(k).equals(myData.get(k - 1))) { myData.remove(k); } k++; } } For example, if myData has the values 3 3 4 4 4 8 7 7 7, after calling removeDups, myData should have the values 3 4 8 7. Which of the following best describes how to fix the error so that removeDups works as intended?

to be edited

Consider the following method, remDups, which is intended to remove duplicate consecutive elements from nums, an ArrayList of integers. For example, if nums contains {1, 2, 2, 3, 4, 3, 5, 5, 6}, then after executing remDups(nums), nums should contain {1, 2, 3, 4, 3, 5, 6}. public static void remDups(ArrayList<Integer> nums) { for (int j = 0; j < nums.size() - 1; j++) { if (nums.get(j).equals(nums.get(j + 1))) { nums.remove(j); j++; } } } The code does not always work as intended. Which of the following lists can be passed to remDups to show that the method does NOT work as intended?

{1, 2, 2, 3, 3, 4, 5}

Directions: Select the choice that best fits each statement. The following question(s) refer to the following information. Consider the following sort method. This method correctly sorts the elements of array data into increasing order. public static void sort(int[] data) { for (int j = 0; j < data.length - 1; j++) { int m = j; for (int k = j + 1; k < data.length; k++) { if (data[k] < data[m]) { m = k; } } int temp = data[m]; data[m] = data [j]; data[j] = temp; } } Question Assume that sort is called with the array {6, 3, 2, 5, 4, 1}. What will the value of data be after three passes of the outer loop (i.e., when j = 2 at the point indicated by / * End of outer loop * /) ?

{1, 2, 3, 5, 4, 6}


Kaugnay na mga set ng pag-aaral

abnormal psych dr nolan tests 1-4

View Set

"How to Use Quizlet" and "Quizlet Live"

View Set

Lab 12-1: Implementing Different Boot Methods and Types of Operating System Installation

View Set

International Affairs - Militant Jihadism to International Terrorism

View Set