I’m often confronted with the following situation: I have some data in a table (nested arrays) and need to loop over all items in it.
Requirements:
- The first item should be identified and handled separately.
- The last item should be identified and handled separately.
- If similiar items are sorted they should be identified in groups with the first and last group item identified. (in this case sort/group by gender)
- Subtotals of group items and total of all items should be given.
DATA:
Comic characters with firstname, lastname, tvshow, gender
assuming to be ordered by gender, lastname.
Turanga|Leela|Futurama|Female
Marge|Simpson|The Simpsons|Female
Eric|Cartman|South Park|Male
Peter|Griffin|Family Guy|Male
Homer|Simpson|The Simpsons|Male
QUESTION:
How would you code a loop (any language welcome!) that produces the following output?
Indention is not important.
OUTPUT:
First Entry: Turanga Leele (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
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:
Output is: