HW1 SAMPLE ANSWERS 1. public static String getUnique(String s1, String s2) { String result = ""; for (int i = 0; i < s1.length(); i++) { for (int j = 0; j < s2.length(); j++) { // Is the pair already in the result string? if (result.indexOf("" + s1.charAt(i) + s2.charAt(j)) == -1) result = result + s1.charAt(i) + s2.charAt(j) + " "); } } // Return result return result; } 2. The maximum length of the string is 2mn + (mn) = 3mn. 2mn comes from the number of combinations of two characters one from each string assuming there are no duplications. The mn term comes from the number of spaces added: one per combination. 3. public static String getUnique(String s1, String s2) { StringBuilder result = new StringBuilder(); for (int i = 0; i < s1.length(); i++) { for (int j = 0; j < s2.length(); j++) { // Is the pair already in the result string? if (result.indexOf("" + s1.charAt(i) + s2.charAt(j)) == -1) result.append("" + s1.charAt(i) + s2.charAt(j) + " "); } } // Return result return result.toString(); // need to explicitly call toString } 4. The StringBuilder version is expected to run faster since it does create a new string every time we append additional characters. Concatenation will create a new string every single time. 5. public static void oneNamePerLine(String s1) { // Precondition: s1 is a string of names, comma-delimited, // all in uppercase // e.g. "TOM,MARGARET,DAVE,TIM,BARBARA,VICTOR,ANGIE,MARK,SCOTT" Scanner stringScan = new Scanner(s1); stringScan.useDelimiter(","); while(stringScan.hasNext()) { System.out.println(stringScan.next()); } } 6. public static int fileSum(String s1){ File myFile = new File(s1); int sum = 0; Scanner filescan; try { filescan = new Scanner(myFile); } catch (FileNotFoundException e) { return 0; // file not found, return immediately } while(filescan.hasNextLine()) { sum += Integer.parseInt(filescan.nextLine()); } return sum; } 7. public static int maxVal(int[] myArray) { int max = myArray[0]; for (int i = 1; i < myArray.length; i++) { if (myArray[i] > max) { max = myArray[i]; } } return max; } 8. public static int maxValIndex(int[] myArray) { int maxIndex = 0; for (int i = 1; i < myArray.length; i++) { if (myArray[i] > myArray[maxIndex]) { maxIndex = i; } } return maxIndex; }