import java.util.ArrayList; /** * Assorted functions for the homework problems. Kept here * because they're reused by other stuff. * @author Ed */ public class Functions { /** * Produce ASCII graphical output of the input list of ComparatorPairs. * Always assumes no more than 10 comparators, draws padding where necessary * (this could be changed but the homework doesn't require it). * @param comparatorList The list of comparators to output graphically. * @returns The list of output strings. */ public static ArrayList outputComparatorGraphic(ArrayList comparatorList) { ArrayList output = new ArrayList(); String bar = ""; int numberOfComparators = 10; for (int i = 0; i < numberOfComparators; i++) { bar += " " + new Integer(i).toString(); } output.add(bar); bar = ""; for (int i = 0; i < numberOfComparators; i++) { bar += "..|"; } output.add(bar); for (int j = 0; j < comparatorList.size(); j++) { bar = ""; Boolean drawingLine = false; ComparatorPair c = comparatorList.get(j); for (int i = 0; i < numberOfComparators; i++) { if (drawingLine) bar += "--"; else bar += ".."; if (i == c.left()) { bar += "o"; drawingLine = true; } else if (i == c.right()) { bar += "o"; drawingLine = false; } else { if (drawingLine) bar += "-"; else bar += "|"; } } output.add(bar); } return output; } /** * This function parses a list of strings and generates from that list a * collection of data types corresponding to the lines of input. Always * assumes 10 comparators; the homework packet does not specify a dynamic * number of comparators. * @param lines The lines of input to parse. * @return A list of ComparatorPairs to correspond to the values on each * line. * @throws java.lang.IllegalArgumentException Not enough lines of data were * passed. */ public static ArrayList outputComparatorList(ArrayList lines) throws IllegalArgumentException { ArrayList c = new ArrayList(); if (lines.size() < 3) throw new IllegalArgumentException("Needs to be at least three lines of input."); for(int i = 2; i < lines.size(); i++) { String foo = lines.get(i); int x = ((foo.indexOf("o") + 1) / 3) - 1; int y = ((foo.lastIndexOf("o") + 1) / 3) - 1; c.add(new ComparatorPair(x, y)); } return c; } /** * Returns a canonical linear output string according to the instructions in * Problem 19. * @param pairs List of comparator pairs to parse. * @return The canonical linear output string. */ public static String makeCanonicalLinearOutput(ArrayList pairs) { String foo = ""; for (int i = 0; i < pairs.size(); i++) { foo += pairs.get(i).toString(); if ((i + 1) % 5 == 0) foo += "\n"; else foo += " "; } return foo; } }