This is a practice test. The actual test may contain fewer or more
questions. The actual test may or may not supply you with other
materials (such as starter code).
package test1;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
public class Practice1A {
private Practice1A() {
}
/**
* The string describing this test version.
*/
public static final String TEST_VERSION = "PRACTICE";
public static String hello(String name) {
return "Hello, " + name;
}
public static String toString(List<Character> t) {
if (t.isEmpty()) {
throw new IllegalArgumentException();
}
String s = "";
for (Character c : t) {
s += c;
}
return s;
}
public static List<Character> shuffle(List<Character> t) {
int n = t.size();
List<Character> result = new ArrayList<>();
for (int i = 0; i < n / 2; i++) {
result.add(t.get(i));
result.add(t.get(i + n / 2));
}
return result;
}
public static List<Character> repeatedChars(String s) {
List<Character> result = new ArrayList<Character>();
/*
* This solution uses a set named t to check if a character appears more than
* once in the string.
*
* Set<Character> t = new HashSet<Character>();
* for (int i = 0; i < s.length(); i++) {
* char c = s.charAt(i);
* if (t.contains(c) && !result.contains(c)) {
* result.add(c);
* }
* t.add(c);
* }
* return result;
*/
/**
* This solution uses Collections.frequency to count the number of times a
* character appears in the string.
*/
List<Character> t = new ArrayList<>();
for (int i = 0; i < s.length(); i++) {
char c = s.charAt(i);
t.add(c);
}
for (Character c : t) {
int n = Collections.frequency(t, c);
if (n > 1) {
if (!result.contains(c)) {
result.add(c);
}
}
}
return result;
}
}
Question 2
Create a text file named answers.txt (use File->New->
Untitled text file in eclipse). Type your answer to the following question in the text file.