我选择了世界上最冗长的语言(Java)来做到这一点,但这应该做你想做的。它只需要一次通过,但需要一行预测。它还需要输入的至少两条线,虽然它会比较容易适应任何的行数:
import java.util.Arrays;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import static java.lang.System.out;
public class Loop {
static enum Col { FIRST_NAME, LAST_NAME, TV_SHOW, GENDER }
private static final List<String[]> characters = Arrays.asList(
new String[] {"Turanga", "Leela", "Futurama", "Female"},
new String[] {"Marge", "Simpson", "The Simpsons", "Female"},
new String[] {"Eric", "Cartman", "South Park", "Male"},
new String[] {"Peter", "Griffin", "Family Guy", "Male"},
new String[] {"Homer", "Simpson", "The Simpsons", "Male"});
public static void summarize(List<String[]> character, Col groupBy) {
assert character.size() > 1;
int total = 0;
Iterator<String[]> i = characters.iterator();
String[] row = next(i);
String[] peek = next(i);
String group;
out.print("First Entry:" + format(row));
Map<String, Integer> subTotals = new HashMap<String, Integer>();
do {
group = col(row, groupBy);
out.print("First " + group + ":");
subTotals.put(group, 0);
do {
out.print(format(row));
total = incrementTotals(total, group, subTotals);
row = peek;
peek = next(i);
} while (peek != null && col(peek, groupBy).equals(group));
total = incrementTotals(total, group, subTotals);
out.print("Last " + group + ":" + format(row));
out.println("--");
out.println("Total " + group + "s:" + subTotals.get(group));
out.println("--");
if (peek == null) break;
row = peek;
peek = next(i);
} while(true);
out.print("Last Entry:" + format(row));
out.println("--");
out.println("Total Entries:" + total);
}
private static String[] next(Iterator<String[]> i) {
if (i.hasNext())
return i.next();
return null;
}
private static int incrementTotals(int total, String group,
Map<String, Integer> subTotals) {
total++;
subTotals.put(group, subTotals.get(group) + 1);
return total;
}
private static String format(String[] row) {
return col(row, Col.FIRST_NAME) + " " + col(row, Col.LAST_NAME)
+ "(" + col(row, Col.TV_SHOW) + ")\n";
}
private static String col(String[] row, Col col) {
return row[col.ordinal()];
}
public static void main(String args[]) {
summarize(characters, Col.GENDER);
}
}
输出是:
First Entry:Turanga Leela(Futurama)
First Female:Turanga Leela(Futurama)
Last Female:Marge Simpson(The Simpsons)
--
Total Females:2
--
First Male:Eric Cartman(South Park)
Peter Griffin(Family Guy)
Last Male:Homer Simpson(The Simpsons)
--
Total Males:3
--
Last Entry:Homer Simpson(The Simpsons)
--
Total Entries:5
令人印象深刻的设计。 – capfu 2009-07-23 09:53:27