THINK FIRST·CODE LATER

← All labs

Separate Chaining with Rehashing

Problem

Read the initial number of buckets m, the number of keys n, and then n integer keys. Insert them in order into a separate-chaining hash table with h(k) = Math.floorMod(k, m), appending each new key to the end of its bucket's list.

  • A key that is already present prints Duplicate: K and is skipped.
  • After a key has been added, if size > m (load factor above 1), resize to 2m + 1 buckets and print Resized to M. Rehash by visiting the old buckets from 0 to m − 1, each from front to back, appending every key to the end of its new bucket.

Finally print each bucket as i: a -> b -> c, or i: (empty), and a summary line.

Input:

2 5 4 1 6 3 9

Output:

Resized to 5
0: (empty)
1: 6 -> 1
2: (empty)
3: 3
4: 4 -> 9
Size: 5, Buckets: 5, Longest chain: 2

(After 4, 1, 6 the table has 3 keys in 2 buckets, so it grows to 5. Bucket 0 held 4 → 6 and is rehashed first, which is why 6 comes before 1 in the new bucket 1.)

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.

d14-2-data-1.txt

2 5 4 1 6 3 9
What your program must print for d14-2-data-1.txt
Resized to 5
0: (empty)
1: 6 -> 1
2: (empty)
3: 3
4: 4 -> 9
Size: 5, Buckets: 5, Longest chain: 2

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

Windows PowerShell does not understand <:

Get-Content d14-2-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.