import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Set;
/**
* A utility class for Test 2.
*
* @author EECS2030
*
*/
public class Test2C {
private Test2C() {}
/**
* Returns the character at the beginning of the string s.
*
* @param s
* a string
* @pre. s.length() > 0
* @return the character at the beginning of s
*/
public static char first(String s) {
return s.charAt(0);
}
/**
* Returns the second character of the string s.
*
* @param s
* a string
* @return the second character of s
* @throws IllegalArgumentException
* if the length of the string is less than 2
*/
public static char second(String s) {
if (s.length() < 2) {
throw new IllegalArgumentException("string must have length of 2");
}
return s.charAt(1);
}
/**
* Returns the longest string contained in the set t. If the set t is empty
* then the empty string is returned.
*
* @param t
* a set of strings
* @return the longest string contained in t, or the empty string if t is
* empty
*/
public static String longest(Set<String> t) {
String result = "";
int len = 0;
for (String s : t) {
if (s.length() > len) {
len = s.length();
result = s;
}
}
return result;
}
/**
* Searches a list of strings for the string that occurs the most
* frequently. For example, if list t is:
*
* <p>
* ["a", "b", "b", "c"]
*
* <p>
* then the string "b" is returned.
*
* <p>
* If more than one string occurs with the greatest frequency then the
* string that comes first in dictionary order is returned. For example, if
* list t is:
*
* <p>
* ["zed", "pop", "pop", "are", "are"]
*
* <p>
* then the string "are" is returned.
*
* @param t
* a list to search
* @pre. t contains at least one string
* @return the string that occurs most frequently in the list
*/
public static String mostFrequent(List<String> t) {
List<String> sorted = new ArrayList<String>(t);
Collections.sort(sorted);
String mostFreq = sorted.get(0);
int max = 1;
String s = sorted.get(0);
int count = 1;
for (int i = 1; i < sorted.size(); i++) {
String next = sorted.get(i);
if (s.equals(next)) {
count++;
if (count > max) {
max = count;
mostFreq = s;
}
} else {
s = next;
count = 1;
}
}
return mostFreq;
}
}