// Program to test solutions to problem #4 on the cse143 midterm, summer 2013. // Fill in your solution to extractShorterThan, then compile and run the program. import java.util.*; public class Test4 { public static Set extractShorterThan(Set s, int n) { // fill in your solution here // you can also rename the parameter above return null; } // this is the sample solution public static Set extractShorterThan2(Set s, int n) { Set result = new TreeSet(); Iterator iter = s.iterator(); while (iter.hasNext()) { String word = iter.next(); if (word.length() < n) { iter.remove(); result.add(word); } } return result; } private static int failCount; public static void main(String[] args) { String[][] data = {{}, {"aa", "bb", "cc"}, {"aa", "bb", "cc"}, {"dog", "puppy", "cat", "bird", "rat", "mouse"}, {"one", "two", "three", "four", "five"}}; int[] ns = {3, 2, 3, 5, 8}; for (int i = 0; i < data.length; i++) { String[] words = data[i]; int n = ns[i]; Set s = new TreeSet(); for (String word : words) { s.add(word); } test(s, n); } if (failCount == 0) { System.out.println("all tests passed"); } else { System.out.println("failed " + failCount + " tests"); } } public static void test(Set s, int n) { System.out.println("set = " + s); System.out.println("n = " + n); Set sCopy = new TreeSet(s); Set result1 = extractShorterThan2(sCopy, n); System.out.println("extracted = " + result1); System.out.println("set after = " + sCopy); boolean fail = false; try { Set result2 = extractShorterThan(s, n); if (!result1.equals(result2) || !sCopy.equals(s)) { fail = true; System.out.println("your extracted = " + result2); } } catch (RuntimeException e) { int line = e.getStackTrace()[0].getLineNumber(); System.out.println(" threw " + e + " at line #" + line); fail = true; } if (fail) { System.out.println("failed"); failCount++; } else { System.out.println("passed"); } System.out.println(); } }