COMPSCI 186

Réussis tes devoirs et examens dès maintenant avec Quizwiz!

What is the logic error? /** Return the sum of the odd numbers from 0 to n, inclusive. */ int sumOddUpTo(int n) { int sum = 0; for (int i = 0; i <= n; i++) { if (i % 2 == 0) { break; } else { sum += i; } } return sum; }

"The body of the if statement mistakenly exits the loop (using break rather than continue), so that this method will always return 0."

What is the logic error? /** Return the mean of the values stored in `a`. */ double mean(int[] a) { if (a.length == 0) { return 0.0; } double x = 0.0; for (int i = 0; i < a.length; i++) { x += i; } return x / a.length; }

"The method mistakenly sums the for loop's i (index), rather than the value at cell i (a[i])."

Write an concise high level description: double mystery(int[] a) { if (a.length == 0) { return 0.0; } double x = 0.0; for (int i: a) { x += i; } return x / a.length; }

"The mystery method returns the mean of the values stored in its parameter a, or 0.0 if the a is empty."

xΔy

(xUy) - (x∩y), a new set of all elements that are not common in both sets

1 point) Suppose you have a single directory on your CLASSPATH, /Users/student/src/. That is, the src directory (located inside student, located inside Users) is on your classpath. Suppose the first line of a Java source file named "Banana.java" is: package produce.fruits; Where exactly should this file be located? Specify the full path to the file. For example, a wrong answer is "in /Users/Banana.java". Another wrong answer is /produce/fruits/Banana.java. C. (2 points) Suppose we add a file named "Broccoli.java" to the project above, and we want the Broccoli class to reside in the produce.vegetables package. What should the first line (the package declaration) of the Broccoli.java file be? And, what should the full path to the file be? D. (1 point) Finally, suppose we want to reference the Broccoli class from within the "Banana.java" source. What import statement must we to add to the Banana.java file? If none is necessary, say so.

/Users/student/src/produce/fruits/Banana.java /Users/student/src/produce/vegetables/Broccoli.java import produce.vegetables.Broccoli;

Suppose you treat the integers as a graph. In other words, there are an infinite number of vertices; 0 is adjacent to -1 and 1; 1 is adjacent to 0 and 2; and so on. This representation is similar to the "number line" that is sometimes used to teach basic arithmetic. If you were to perform a breadth-first search, starting at 0 and with a goal of 3, in what order would the integers be visited? Assume that the neighbors of each integer are returned in their natural order (for example, the neighbors of 0 are -1 and 1, in that order).

0, -1, 1, -2, 2, -3, 3.

What are the three questions of recursion?

1) do you have a base case? 2)do the calls make progress? 3)is the algorithm correct?

Suppose you have a BananaVendor class with the following instance variables, each of which must be considered when considering equality: private int bananaCount; private List<String> varieties; private Banana banana; A. (1 point) Write a valid equals method for the BananaVendor class. B. (1 point) Write a valid hashCode method for the BananaVendor class. For full credit, your answer must both obey the hashCode contract as well as attempt to return distinct integers for distinct objects.

@Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; BananaVendor other = (BananaVendor) obj; if (banana == null) { if (other.banana != null) return false; } else if (!banana.equals(other.banana)) return false; if (bananaCount != other.bananaCount) return false; if (varieties == null) { if (other.varieties != null) return false; } else if (!varieties.equals(other.varieties)) return false; return true; } public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((banana == null) ? 0 : banana.hashCode()); result = prime * result + bananaCount; result = prime * result + ((varieties == null) ? 0 : varieties.hashCode()); return result; }

Test the isLetterOrDigit method of Character on each of the characters 'A', '&', and '2'. (Use three assertions, all in one method.)

@Test public void testIsLetterOrDigit() { assertTrue(Character.isLetterOrDigit('A')); assertFalse(Character.isLetterOrDigit('&')); assertTrue(Character.isLetterOrDigit('2')); }

Test the max method of Math on two int arguments of your choice.

@Test public void testMax() { assertEquals(1, Math.max(1, -1)); }

Test the min method of Math on two int arguments of your choice.

@Test public void testMin() { assertEquals(-1, Math.min(1, -1)); }

Test the toLowerCase method of String on the string "ASDF".

@Test public void testToLowerCase() { assertEquals("asdf", "ASDF".toLowerCase()); }

What is a set?

A Set is an unordered collection of unique elements. There are no indexes assigned to elements in a Set, and the size is unbounded.

What is a tree?

A connected graph with no cycles

What is a static method?

A method not evaluated in context of an object

What is recursion?

A programming technique in which a method calls itself.

What is bubble sort?

A sorting algorithm that only swaps with the numbers next to each other. Start at the right hand side. sort next two if not in sorted order, if in order, continue to next number.

what is a binary tree?

A tree in which each node can have only two children: a left child and a right child.

Suppose we write lists by listing the values of the elements between curly braces (note: code below was corrected after the due date to show curly braces). For example, the list {1, 3, 5, 7} represents a List of Integers, containing the first four odd numbers. Let odd = {1, 3, 5, 7} and even = {8, 6, 4, 2}. Assume each of the following happens in sequence, that is, if odd is modified in one question, carry that value forward into the next question. (1 point each) A. What is the contents of odd if we call odd.addAll(even)? B. What is the contents of odd if we then call odd.sort(null)? (You may want to go look at the Java API here, but in short: it does what you'd expect.) C. What is the contents of odd if we then call odd.removeAll(even)? D. What is the contents of odd if we then call odd.retainAll(even)?

A. What is the contents of odd if we call odd.addAll(even)? {1, 3, 5, 7, 8, 6, 4, 2} B. What is the contents of odd if we then call odd.sort(null)? {1, 2, 3, 4, 5, 6, 7, 8} C. What is the contents of odd if we then call odd.removeAll(even)? {1, 3, 5, 7} D. What is the contents of odd if we then call odd.retainAll(even)? {} (an empty list)

what is a map?

An ADT that associates keys and values, has no order.

what is the worst case run time of: ArrayList.get() HashSet.contains() LinkedList.indexOf()

ArrayList.get(): constant time HashSet.contains(): constant time LinkedList.indexOf(): linear in the length of the list

Objects have ____ and _____

Behaviors and states

what is insertion sort?

Breaks data into sorted and unsorted, moves things from sorted to unsorted.

(3 points) Given the following code, what is the output? Assume a public number instance variable, and a equals() method that uses only this instance variable to check if two Bus objects values' are semantically equal. Bus busA = new Bus(); Bus busB = new Bus(); busA.number = 44; busB.number = 44; System.out.println(busA == busB); System.out.println(busA.equals(busB)); Bus busC = busB; busB = busA; busA.number = 13; System.out.println(busA == busC); System.out.println(busA.equals(busC)); busC = busB; System.out.println(busA == busC); System.out.println(busA.equals(busC));

Expected output: false true false false true true

(1 point) Why does the method not return the correct value? (1 point) What specific stylistic choice is the cause of the problem? (1 point) Rewrite the method to return the correct result. Remove unnecessary variables and convert the while loop to a for loop. int countMatchingChars(String string, char toMatch) { int count = 0; boolean isMatched = false; int i = 0; while (i < string.length()) if (string.charAt(i) == toMatch) isMatched = true; count++; i++; if (isMatched) return count; else return 0; }

For any string of length > 0, it gets stuck in an infinite loop The failure to wrap the if and while statement bodies in curly braces {}. Indentation does not determine blocks extent in Java, only curly braces. int countMatchingChars(String string, char toMatch) { int count = 0; for (int i = 0; i < string.length(); i++) { if (string.charAt(i) == toMatch) { count++; } } return count; }

What is a node in a linked list?

Holds one element of a linked, contents can not be changed later on.

How do you create a new list?

List<E> name = new ArrayList<>();

A. (1 point) Suppose you want to store a map between Strings and sets of lists of chars, where each list of chars is a permutation of the characters of the String. What would the full, legal Java type of this map be?

Map<String, Set<List<Character>>>

can a map have duplicate keys?

NOPE, but it can have duplicate values

Object address X and Y are both pointing to different string objects that contain the same string. Is X==Y?

No, because they both point to different places in memory.

https://people.cs.umass.edu/~liberato/courses/2018-fall-compsci186/images/homeworks/17-graph.svg If you were to perform a breadth-first search, starting at S and trying to reach either of the two goal vertices (G1 or G2), in what order would the vertices be added to the frontier? Use the BFS algorithm we covered in class (findPath). Assume that the neighbors of each vertex are returned in alphabetical order. For example, the only neighbors of S are A and B, in that order. But neither B nor A are neighbors of S. C. (1 point) What is the first path from S to one of the goal vertices that this search would return?

S, A, B, C, D, E, G2, G1 S, A, D, G2

In the following method, (i) identify base case(s), (ii) identify the recursive case(s), and (iii) state whether the method will always terminate normally, without throwing an exception. If (i) or (ii) are implicit, then note what they depend upon; or, if (i) or (ii) are missing, then note that fact. static int fib(int n) { if (n == 0) { return 1; } else { return fib(n - 1) + fib(n - 2); } }

The base case is when n == 0. Arguably a base case for n == 1 is missing. The recursive case is when n > 0 (or n > 1, if you argue that n == 1 is a missing base case). The method will not always terminate normally. For n > 0, it will skip the base case and recurse into negative numbers until it blows the call stack.

What is the start of a linked list called? what does it do?

The head, points to the first element of the linked list.

Write a concise high level description: int mystery(char c, String s) { int x = 0; for (char k : s.toCharArray()) { if (c != k) { x++; } } return x; }

The mystery method returns the number of characters in s that aren't equal to c".

What is the end of a linked list called?

The tail.

What are some pros and cons of using an array?

They have a fixed size, but elements can be accessed in constant time, easy to trigger a NullPointerException

identify a logic error in a short snippet of code. That is, you will find a conceptual error, not an error that the compiler would catch. Here is an example: /** * Swaps the `i`th and `j`th elements of the List `l`. * Assume 0 <= i <= j <= l.size(). */ public static void swap(List<Integer> l, int i, int j) { l.set(i, l.get(j)); l.set(j, l.get(i)); }

This method overwrites the element at i with the element at j, but does not overwrite the element at j with the element at i. (A temp variable is needed.)

write a concise, high-level, English description of the code's action. public static List<Integer> mystery(List<Integer> l, int i) { List<Integer> r = new ArrayList<>(); for (int j = i; j < l.size(); j++) { r.add(l.get(j)); } return r; }

This method returns a new list composed of the last but i elements of l in the order they appear in l.

What does public final mean?

Variable value can not be changed later

What is selection sort?

We first find the minimum value in the array and put it first. Then find the next smallest and put it second and so on until the list is sorted.

What is constant time?

What the runtime is constant, not dependent on variable or data structure size.

Object address X and Y are both pointing to different string objects that contain the same string. Is X.equals(Y)?

Yes, because while they point to different places in memory (different objects) the content of those objects are the same.

can you iterate through a set?

Yes, but only using for (E e: s)

what are edges?

a connection between vertices

What is a queue?

a first in first out data structure

What is a complex graph?

a graph where all possible edges exist. all vertex adjacent to all other vertex.

what is an undirected graph?

a graph with no specific pointer direction

What is a stack?

a last in first out data structure

What is the main difference between a list and an array

a list is unbounded

what is a graph path?

a sequence of edges in a graph.

set intersection

a set of all the elements that are common to both sets.

what is a graph?

a set of vertices and edges

What is a graph?

a set of vertices and edges G = {v,e}

what is a connected component?

a set of vertices where each vertex in the set has a path to each other vertex in the set.

What is breadth-first search?

algorithm for traversing or searching tree or graph data structures. It starts at the tree root, and explores all of the neighbor nodes at the present depth prior to moving on to the nodes at the next depth level.

What is a depth fist search?

algorithm for traversing or searching tree or graph data structures. The algorithm starts at the root node and explores as far as possible along each branch before backtracking.

what is the add time of a binary tree?

almost constant time

What is a vertex?

an element in a graph (aka a node)

symmetric difference

an operation applied to two sets to create a new set containing all elements in exactly one of the original sets (all the elements that does not overlap between the sets)

write a method which, given a String, returns true if and only if the count of the number of times the lowercase 'a' appears in the string is divisible by 7. The method's signature should be boolean aCountDivisibleBySeven(String string)

boolean aCountDivisibleBySeven(String string) { int count = 0; for (int i = 0; i < string.length(); i++) { if (string.charAt(i) == 'a') { count++; } } return count % 7 == 0; }

Write a method which, given two int arrays, determines whether the values in the first array a are a subset of the values in the second array b. In other words, return true if and only if every value in a is also present in b. Your method should have the signature boolean isSubset(int[] a, int[] b).

boolean isSubset(int[] a, int[] b) { for (int i: a) { boolean iFound = false; for (int j: b) { if (i == j) { iFound = true; break; } } if (!iFound) { return false; } } return true; }

Suppose you have an empty stack, and you execute the following operations: push(1); push(2); push(3); peek() pop(); push(1); pop(); pop(); What are the contents of the stack? Be sure to clearly indicate the top and bottom of the stack.

bottom -> [1] <- top

A. (3 points) Assume you have List containing a million elements of type String. Would you generally expect the following operations be faster with an array-based implementation, or faster with a linked-list-based implementation (with only a head pointer, no other instance variables)? Assume the array-based implementation's backing array is large enough to hold the new element (no enlarge() needed). Assume each of the following operations takes the same amount of time: array lookups, setting elements of arrays, creating new nodes, traversing a single link in a linked list, and assigning a reference (like, calling setNext on a node). calling size() adding an element to the end of the list (add(Marc)) adding an element to the front of the list (add("Marc", 0))

calling size() - array-based (since it could just return the size instance variable) adding an element to the end of the list (add(Marc)) - array-based (can directly jump to the end) adding an element to the front of the list (add("Marc", 0)) - linked-list-based (a pair of assignments to Node references is faster than moving every item in an array)

A. (1 point) Write a minimal definition for a class named MonthDay, about which you know nothing else (that is, don't use the information in the following questions in this answer). Your answer to this question should be just the minimal definition - it will be really short! B. (2 points) Add a constructor for MonthDay that takes a month and day (of the appropriate primitive type), and stores these values in appropriately-named instance variables. If the month or day is obviously invalid, then your constructor should throw an IllegalArgumentException. Do not exhaustively check correctness. Instead, limit your checks to checking for a day greater than zero, and a month between 1 and 12 inclusive. Your answer should be the entire class definition. C. (1 point) Write a public toString() method with an appropriate signature that converts the MonthDay object to a String representation as exemplified by "31 January" or "4 March". Your answer should be just the toString() method.

class MonthDay { } public class MonthDay { private int month; private int day; public MonthDay(int month, int day) { if (month < 1 || month > 12 || day <= 0) { throw new IllegalArgumentException(); } this.month = month; this.day = day; } } public String toString() { String str = day + " "; switch (month) { case 1: str += "January"; break; case 2: str += "February"; break; case 3: str += "March"; break; case 4: str += "April"; break; case 5: str += "May"; break; case 6: str += "June"; break; case 7: str += "July"; break; case 8: str += "August"; break; case 9: str += "September"; break; case 10: str += "October"; break; case 11: str += "November"; break; case 12: str += "December"; break; } return str; }

State the approximate worst-case running time for each of the following. ArrayList.size

constant time

State the approximate worst-case running time for each of the following. int manhattanDistance(int x1, int y1, int x2, int y2) { return Math.abs(x2 - x1) + Math.abs(y2 - y1); }

constant time

xUy

creates a new set containing all the elements of x and y

x∩y

creates a new set containing elements common to both x and y

a map is ____ to get and _____ to iterate.

fast to get, slow to iterate.

what is a search tree?

for every node, all left children are smaller and all right children larger

what is the map method that returns a value if present, if not returns a default?

getOrDefault(key,def)

What makes two graph vertices adjacent?

if an edge exists between the two vertices

IFF

if and only if

B. (1 point) Suppose you had a Map<Integer, List<Integer>>. Write a method that returns the sum of all integers stored in all keys (not values) of the map, or zero if there are no keys.

int methodB(Map<Integer, List<Integer>> map) { int sum = 0; for (Integer i : map.keySet()) { sum += i; } return sum; }

C. (1 point) Suppose you had a Map<Integer, List<Integer>>. Write a method that returns the sum of all integers stored in all values (not keys) of the map (or within the collection(s) stored in the values), or zero if there are no such values.

int methodC(Map<Integer, List<Integer>> map) { int sum = 0; for (List<Integer> l : map.values()) { for (Integer i : l) { sum += i; } } return sum; }

D. (2 points) Suppose you had a Map<String, List<List<Integer>>>. Write a method that returns the sum of all integers stored in all values (or within the collection(s) stored in the values) of the map corresponding to keys that start with "a", or zero if there are no such values.

int methodD(Map<String, List<List<Integer>>> map) { int sum = 0; for (String k: map.keySet()) { if (k.startsWith("a")) { for (List<Integer> l : map.get(k)) { for (Integer i : l) { sum += i; } } } } return sum; }

how do you return a set of map keys?

keySet()

State the approximate worst-case running time for each of the following. void reverse(int[] a) { for (int front = 0; front < a.length / 2; front++) { int rear = a.length - 1 - front; int t = a[front]; a[front] = a[rear]; a[rear] = t; } }

linear in a.length

what is the worst case run time of: int sum(int[] a) { int s = 0; for (int i : a) { s += i; } return s; }

linear in the length of the array

State the approximate worst-case running time for each of the following. ArrayList(Collection<? extends E> c) (that is, the copy constructor for ArrayList)

linear in the size() of the input

State the approximate worst-case running time for each of the following. Arrays.binarySearch(array, value)

logarithmic in the length of the input

How do you create a new array?

new E[size] name;

Suppose we have sets of integers S and T, and we have corresponding Java objects of type Set<Integer> named s and t. Are each of the following equivalent? Explain your answer in a single sentence C. S ∪ T and s.addAll(t)

no; the former is the union of two sets, and modifies s; or, only if explained clearly: yes; the former is the union of two sets, and the latter modifies s to be the union of the two sets (the goal of this question was for you to think about the difference between mathematical notation and how addAll differs from union)

Write a generic class MyList<E> that extends an existing implementation of List. MyList should include a method public List<E> reversed(). reversed returns a new list consisting of the elements of the current list in reverse order. reversed must not modify the list. For full credit, your method must correctly use generic types, and must not contain unnecessary method calls or loops, even if they do not otherwise impact correctness. You may assume List and ArrayList are correctly imported from java.util. You may not import other classes.

public List<E> reversed() { List<E> l = new ArrayList<>(); for (int i = this.size() - 1; i >= 0; i--) { l.add(get(i)); } return l; }

(1 point) Suppose you have a linked list composed of Nodes: public class Node<E> { public Node<E> next; public E data; } (1 point) Write a recursive definition (not the code) for contains, in the style from lecture. (1 point) Implement boolean contains(Node<Integer> node, int e) using recursion - no explicit loop constructs (for, while) allowed!

public boolean contains(Node<Integer> node, int e) { if (node == null) { return false; } if (node.data == e) { return true; } return contains(node.next, e); }

Write a recursive definition (not the code) for contains on a linked list of Node<E>, starting at a given node, in the style from lecture. Then, implement boolean contains(Node<Integer> node, int e) using recursion - no explicit loop constructs (for, while) allowed!

public boolean contains(Node<Integer> node, int e) { if (node == null) { return false; } if (node.data == e) { return true; } return contains(node.next, e); }

(1 point) Suppose you have a linked list composed of Nodes: public class Node<E> { public Node<E> next; public E data; } Write an iterative method boolean contains(Node<Integer> node, int e) that returns true if and only if the list starting at node contains the given integer.

public boolean contains(Node<Integer> node, int e) { while (node != null) { if (node.data == e) { return true } node = node.next; } return false; }

Suppose you want to sort a list of integers into descending order. Write a class DescendingIntegerComparator that implements Comparator. It should allow you to use List.sort to perform this task. For example, if the unsorted list is [2, 1, 4, 3], then the list should be [4, 3, 2, 1] after sorting using this comparator.

public class DescendingIntegerComparator implements Comparator<Integer> { public int compare(Integer o1, Integer o2) { return -Integer.compare(o1, o2); } }

Define a class Dog. A Dog instance has a name (which could change), a breed (which is immutable, that is, it cannot change) and a licenseNumber (an integer between 1 and 1,000,000, which is immutable). Two Dog instances are considered equal if and only if their licenseNumbers are equal. Your definition should include the constructor and the equals method, but should elide the getters and setters.

public class Dog { private String name; private final String breed; private final int licenseNumber; public Dog(String n, String b, int l) { name = n; breed = b; licenseNumber = l; } public boolean equals(Dog o) { return (licenseNumber == o.licenseNumber); } }

Write a generic class MyList<E> that extends an existing implementation of List. MyList should include a method public List<E> reversed(). reversed returns a new list consisting of the elements of the current list in reverse order. reversed must not modify the list. For full credit, your method must correctly use generic types, and must not contain unnecessary method calls or loops, even if they do not otherwise impact correctness. You may assume List and ArrayList are correctly imported from java.util. You may not import other classes.

public class MyList<E> extends ArrayList<E> { public List<E> reversed() { List<E> reversed = new ArrayList<>(); for (int i = size() - 1; i >= 0; i--) { reversed.add(get(i)); } return reversed; } }

Define a Comparator for Strings such that a sort call on a List<String> of strings sorts the strings by length, shortest to longest. Show the entire class definition. For example, on input list ["ear", "za", "cabaret"], the list sorted according to this comparator will be ["za", "ear", "cabaret"]

public class StringLengthComparator implements Comparator<String> { public int compare(String o1, String o2) { if (o1.length() < o2.length()) { return -1; } else if (o1.length() > o2.length()) { return 1; } return 0; } }

(2 points) Write a public int indexOf(String s) method that searches a StringLinkedList for the first occurrence of a value .equal to s, and returns its index. Return -1 if the value is not found. For this question, write the method assuming that it's part of the StringLinkedList we started in lecture.

public int indexOf(String s) { if (head == null) return -1; int i = 0; for (StringCell current = head; current != null; current = current.getNext()) { if (current.getValue().equals(s)) { return i; } i++; } return -1; }

Write a method public static <E> List<E> notIn(List<E> list, Set<E> set). notIn should return a list that contains the elements present in list but not present in set. The original list and set must not be modified. For full credit, your method must correctly use generics, and must not contain unnecessary method calls or loops, even if they do not otherwise impact correctness. You may assume List, Set, ArrayList, and HashSet are correctly imported from java.util. You may not import other classes.

public static <E> List<E> notIn(List<E> list, Set<E> set) { List<E> l = new ArrayList<>(); for (E e: list) { if (!set.contains(e)) { l.add(e); } } return l; } OR public static <E> List<E> notIn(List<E> list, Set<E> set) { List<E> l = new ArrayList<>(list); l.removeAll(set); return l; }

Write a method public static <E> List<E> notIn(List<E> list, Set<E> set). notIn should return a list that contains the elements present in list but not present in set. The original list and set must not be modified. For full credit, your method must correctly use generics, and must not contain unnecessary method calls or loops, even if they do not otherwise impact correctness. You may assume List, Set, ArrayList, and HashSet are correctly imported from java.util. You may not import other classes.

public static <E> List<E> notIn(List<E> list, Set<E> set) { List<E> result = new ArrayList<>(); for (E e: list) { if (!set.contains(e)) { result.add(e); } } return result; } OR public static <E> List<E> notIn(List<E> list, Set<E> set) { List<E> result = new ArrayList<>(list); result.removeAll(set); return result; }

Write a method static List<Integer> concatenate(List<Integer> l1, List<Integer> l2). concatenate should return, as a new list, all the elements of l1 followed by all the elements of l2, in the order they appeared. Your code must not modify l1 or l2. For example, with an input of l1 = [1, 2, 5], l2 = [2, 4, 1]', it should return the list[1, 2, 5, 2, 4, 1]`.

public static List<Integer> concatenate(List<Integer> l1, List<Integer> l2) { List<Integer> r = new ArrayList<>(l1); r.addAll(l2); return r; }

Write a method static List<Integer> expand(List<Integer> list). For a given list of integers, expand should return a list of those integers, such that each integer i appears i consecutive times in the list. You may assume all integers in the list are non-negative. For example, if list = [1, 4, 2], then expand should return the list [1, 4, 4, 4, 4, 2, 2]. expand must not modify the list.

public static List<Integer> expand(List<Integer> list) { List<Integer> l = new ArrayList<>(); for (int i: list) { for (int j = 0; j < i; j++) { l.add(i); } } return l; }

Suppose we have a singly linked-list-based implementation of a Queue<E>, built of Node<E> elements that link to one another. The Node<E> class has a public Node<E> next and a public E data instance variable. The Queue<E> has head and tail instance variables, pointing to the first and last Nodes of the list (or null if the list is empty), as well as an int size. In other words, it is the implementation we wrote in lecture. Write the void add(E e) method.

public void add(E e) { Node<E> node = new Node<>(); node.data = e; if (head == null) { head = node; } else { tail.next = node; } tail = node; size++; }

public static void reverse(Queue queue) { Stack stack = new Stack(); // TODO } (2 points) Fill in this method such that that when it returns, the order of the items in the queue is reversed. Do not allocate any new structures (like an array or list); use only the defined queue and stack, so that once the list terminates, the queue is reversed.

public void reverse(Queue queue) { Stack stack = new Stack(); while (!queue.isEmpty()) stack.push(queue.remove()); while (!stack.isEmpty()) queue.add(stack.pop()); }

how do you add a value to a map?

put(key,value)

State the approximate worst-case running time for each of the following. int allPairsProductSum(int[] a) { int result = 0; for (int i: a) { for (int j: a) { result += i * j; } } return result; }

quadratic in a.length

what is the worst type of run time?

quadratic time.

what does .peek() do

returns whats at the top of the stack but does not remove it

how do you create a new set?

set<E> name = new HashSet<>();

how do you remove an item from a stack

stack.pop()

B. (2 points) Suppose you have a List<E>. Write a generic static method rotations that returns a Set<List<E>> consisting of the full set of unique rotations of its input. You can use Collections.rotate to rotate the input list. The input list should be unmodified after this method returns. For example: If the input is the list [1, 2, 1, 2], the output would be the set of two lists {[1, 2, 1, 2], [2, 1, 2, 1]}. If the input is the list [1, 2, 3], the output would be the set of three lists {[1, 2, 3], [2, 3, 1], [3, 1, 2]}.

static <E> Set<List<E>> rotations(List<E> list) { Set<List<E>> set = new HashSet<List<E>>(); for (int i = 0; i < list.size(); i++) { List<E> l = new ArrayList<E>(list); Collections.rotate(l, i); set.add(l); } return set; }

A. (2 points) Suppose you have a List<E>. Write a generic static method deduplicate that modifies the list in-place, removing all but one of any element that the list contains, and leaving the list otherwise unchanged - specifically, do not change its order! Items are considered duplicates according to the semantics of their equals method. For example, the after deduplication, the list [3, 1, 2, 1, 3, 4] would be changed to [3, 1, 2, 4].

static <E> void deduplicate(List<E> list) { for (int i = 0; i < list.size(); i++) { E e = list.get(i); int j = i + 1; while (j < list.size()) { if (list.get(j).equals(e)) { list.remove(j); } else { j++; } } } }

(1 point) Write an iterative method int sumOfDigits(int x) that returns the sum of the digits of an integer. If x is 1234, the function should return 1 + 2 + 3 + 4, that is, 10. If x is 345, the function should return 3 + 4 + 5 = 12. If x is 3, the function should return 3. If x is negative, ignore the minus sign. For example, -12 and 12 both return 3. (Hint: You can use x % 10 and x / 10 to get "the last digit" and "the rest of the digits," respectively.) (1 point) Now, implement int sumOfDigits(int x) using recursion - no explicit loop constructs (for, while) allowed!

static int sumOfDigits(int x) { // `static` optional x = Math.abs(x); // or something equivalent int sum = 0; // note boundary condition here! *not* (x > 9), // unless you add the last digit outside the loop! while (x > 0) { sum = sum + (x % 10); x = x / 10; } return sum; } static int sumOfDigits(int x) { // `static` optional x = Math.abs(x); // or equivalent if (x < 10) { return x; } else { return (x % 10) + sumOfDigits(x / 10); } }

Write a method static void removeFromMultiMap(Map<Integer, List<String>> map, Integer key, String value). removeFromMultiMap must remove the value, if present, from the list, if present, associated with the given key. If either is not present it should return without raising an exception. You may assume all keys in the map are associated with non-null values.

static void removeFromMultiMap(Map<Integer, List<String>> map, Integer key, String value) { if (map.containsKey(key)) { map.get(key).remove(value); } }

union of sets

the combination of all elements from two or more sets

Relative Complement / set theoretical difference

the set of all elements in X that are not in Y

x\y or x-y

the set of all elements in X that are not in Y (directional)

what is quadratic time?

when a function takes a.length * a.length time to complete, can occur when there are nested for loops.

what is linear time?

when a functions runtime increase linearly in regards to the length of an element. for example, a single for loop that loops through every element of a list.

x⊂y

x is a subset of y

x∈y

x is an element of set y

Suppose we have sets of integers S and T, and we have corresponding Java objects of type Set<Integer> named s and t. Are each of the following equivalent? Explain your answer in a single sentence A. 1 ∈ S and s.contains(1)

yes; each is true iff (if and only if) the set S contains the value 1.

Suppose we have sets of integers S and T, and we have corresponding Java objects of type Set<Integer> named s and t. Are each of the following equivalent? Explain your answer in a single sentence B. S ⊆ T and t.containsAll(s)

yes; each is true iff the set T contains every element in set S

Suppose A = {1, 2, 3} and B = {2, 4, 6}. What is A ∩ B?

{2}

Suppose you have the array of numbers [3 2 5 4 1]. A. (1 point) In the style we showed in class, show the contents of the array during a selection sort.

| 3 2 5 4 1 *1* | 2 5 4 *3* 1 2 | 5 4 3 1 2 *3* | 4 *5* 1 2 3 4 | 5 1 2 3 4 5 |

Suppose you have the array of numbers [3 2 5 4 1]. A. (1 point) In the style we showed in class, show the contents of the array during a insertion sort.

| 3 2 5 4 1 3 | 2 5 4 1 *2* *3* | 5 4 1 2 3 5 | 4 1 2 3 *4* *5* | 1 2 3 4 *1* *5* | 2 3 *1* *4* 5 | 2 *1* *3* 4 5 | *1* *2* 3 4 5 |


Ensembles d'études connexes

MKTG 371 - QUIZ 3 (Ch. 14, 15, 16)

View Set

HTHRHSC 2500 Med Term Application 4

View Set

ежедневные слова 3

View Set

Chapter 4 Intro to Marketing Fallin KSU

View Set

Chapter 12: Ensuring Quality in Picture Archiving and Communication Systems With Chapter 12 & 13 Quiz

View Set

Prep-U Chapter 21 Putting It All Together

View Set

Relias-Data Collection, Behaviors, and Decisions

View Set