THINK FIRST·CODE LATER

← All labs

Name rankings: maps inside maps

Problem

A registry publishes, for each year, the ranking of the most popular first names for boys and for girls. Write NameRanks.

Data — lines year rank boyName girlName until a line ---. Store them in two nested maps, year → (name → rank): one for boys, one for girls. Use a TreeMap for the years.

Queries — until the end of the input:

  • rank 2021 Noor — the rank(s) of a name in a year;
  • history Sam — its rank in every year where it appears, in order of year;
  • both 2021 — the names used for both boys and girls that year (set intersection), alphabetically;
  • always — the names ranked in every year.

For the input

2020 1 Liam Mia
2020 2 Noor Ava
2020 3 Sam Noor
2021 1 Noor Sam
2021 2 Liam Mia
2021 3 Kai Noor
2022 1 Kai Ava
2022 2 Sam Kai
2022 3 Liam Mia
---
rank 2021 Noor
rank 2020 Kai
history Sam
history Zed
both 2021
both 2022
both 1999
always

the program prints

Noor in 2021: boys' rank 1 girls' rank 3
Kai is not ranked in 2020
History of Sam: 2020=3 2021=1 2022=2
History of Zed: never ranked
Used for both in 2021: [Noor]
Used for both in 2022: [Kai]
Used for both in 1999: []
Ranked every year: [Liam, Mia, Sam]

Data for this lab

Your program reads its data from standard input. Download the file, then give it to your program as shown below. Start with data set 1: its expected output is given.

d5-9-data-1.txt — first 14 lines of 18

2020 1 Liam Mia
2020 2 Noor Ava
2020 3 Sam Noor
2021 1 Noor Sam
2021 2 Liam Mia
2021 3 Kai Noor
2022 1 Kai Ava
2022 2 Sam Kai
2022 3 Liam Mia
---
rank 2021 Noor
rank 2020 Kai
history Sam
history Zed
What your program must print for d5-9-data-1.txt
Noor in 2021: boys' rank 1 girls' rank 3
Kai is not ranked in 2020
History of Sam: 2020=3 2021=1 2022=2
History of Zed: never ranked
Used for both in 2021: [Noor]
Used for both in 2022: [Kai]
Used for both in 1999: []
Ranked every year: [Liam, Mia, Sam]

Run your program first, then open this and compare line by line: your output must contain these lines exactly.

How to give the file to my program

Terminal (macOS, Linux, or Windows Command Prompt), after compiling:

java Main < d5-9-data-1.txt

Windows PowerShell does not understand <:

Get-Content d5-9-data-1.txt | java Main

IntelliJ IDEA: Run → Edit Configurations → Redirect input from. Or simply paste the content of the file into the console when the program waits for input.

Write it here or in your IDE, then paste it. Compile and test it yourself before comparing. Your code stays in your browser — it is never sent to or stored on the server.