THINK FIRST·CODE LATER

← All labs

Answer cache with TTL and LRU eviction

Problem

Before the midterm many students ask Buddy the same questions. Add a cache in front of the (expensive) AI call.

Input: first line capacity ttl costPerCall (capacity ≥ 1 entries, ttl in minutes, cost in yuan). Then lines time question... with non-decreasing times in minutes. Questions are compared after trimming, converting to lower case and collapsing multiple spaces into one.

For each request:

  • if the normalized question is in the cache and time - storedTime < ttl, it is a hit: print t: HIT <normalized question> and mark the entry as most recently used (its stored time does not change);
  • otherwise it is a miss: print t: MISS <normalized question> (call the AI), store it with the current time (replacing an expired entry), and if the cache now holds more than capacity entries, evict the least recently used one and print evicted: <question>.

At the end print Hits: h, Misses: m, Hit rate: x% (one decimal) and AI cost: c yuan, saved: s yuan (two decimals), where cost = misses × costPerCall and saved = hits × costPerCall.

Input:

2 60 0.05
0 What is polymorphism?
5 what is  POLYMORPHISM?
10 What is a class?
12 What is an interface?
15 What is polymorphism?
72 What is an interface?

Output:

0: MISS what is polymorphism?
5: HIT what is polymorphism?
10: MISS what is a class?
12: MISS what is an interface?
  evicted: what is polymorphism?
15: MISS what is polymorphism?
  evicted: what is a class?
72: MISS what is an interface?
Hits: 1, Misses: 5, Hit rate: 16.7%
AI cost: 0.25 yuan, saved: 0.05 yuan

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.

s6-4-data-1.txt

2 60 0.05
0 What is polymorphism?
5 what is  POLYMORPHISM?
10 What is a class?
12 What is an interface?
15 What is polymorphism?
72 What is an interface?
What your program must print for s6-4-data-1.txt
0: MISS what is polymorphism?
5: HIT what is polymorphism?
10: MISS what is a class?
12: MISS what is an interface?
  evicted: what is polymorphism?
15: MISS what is polymorphism?
  evicted: what is a class?
72: MISS what is an interface?
Hits: 1, Misses: 5, Hit rate: 16.7%
AI cost: 0.25 yuan, saved: 0.05 yuan

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

Windows PowerShell does not understand <:

Get-Content s6-4-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.