THINK FIRST·CODE LATER

← All labs

A tiny search engine: the inverted index

Problem

Write InvertedIndex. The first line is n; the next n lines are the text. Build a TreeMap<String, TreeSet<Integer>> mapping each word (lower case, letters only) to the set of line numbers where it occurs. Print the number of distinct words and the word that appears on the most lines (the first in alphabetical order on a tie).

Each remaining line is a query of one or more words: print the lines that contain all of them (retainAll), or not found.

For the input

4
The quick brown fox
jumps over the lazy dog
The dog barks
A quick red fox
fox
the dog
quick fox
cat
the cat

the program prints

Distinct words: 11
On the most lines: the [1, 2, 3]
fox: lines [1, 4]
the + dog: lines [2, 3]
quick + fox: lines [1, 4]
cat: not found
the + cat: not found

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-6-data-1.txt

4
The quick brown fox
jumps over the lazy dog
The dog barks
A quick red fox
fox
the dog
quick fox
cat
the cat
What your program must print for d5-6-data-1.txt
Distinct words: 11
On the most lines: the [1, 2, 3]
fox: lines [1, 4]
the + dog: lines [2, 3]
quick + fox: lines [1, 4]
cat: not found
the + cat: not found

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-6-data-1.txt

Windows PowerShell does not understand <:

Get-Content d5-6-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.