I picked the world's most verbose language to do this in (Java), but this should do what you want. It requires only a single pass, but needs one row of look ahead. It also requires at least two lines of input although it would be relatively easy to adapt to any number of lines:
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);
}
}
Output is:
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