THINK FIRST·CODE LATER

← All labs

Good and bad hash functions

Problem

Write HashQuality with two hash functions for strings:

  • sumHash(s) — the sum of the character codes;
  • polyHash(s) — the polynomial hash h = 31·h + c for each character (what String.hashCode() computes).

Read the number of buckets m, then words. Put each word in bucket hash mod m for both functions (use Math.floorMod for the polynomial hash, which can be negative) and print, for each function, the bucket sizes, the number of buckets used, the collisions (each word after the first in a bucket) and the longest chain. Finally check that polyHash equals String.hashCode() for the first word.

For the input

7 listen silent enlist tinsel inlets stop pots tops spot opts post

the program prints

11 words, 7 buckets, load factor 1.57
sum of characters: buckets [0 0 0 0 5 0 6]
  used 2 of 7, collisions 9, longest chain 6
polynomial (31): buckets [0 1 3 0 2 2 3]
  used 5 of 7, collisions 6, longest chain 3
polyHash matches String.hashCode(): true

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

7 listen silent enlist tinsel inlets stop pots tops spot opts post
What your program must print for d14-6-data-1.txt
11 words, 7 buckets, load factor 1.57
sum of characters: buckets [0 0 0 0 5 0 6]
  used 2 of 7, collisions 9, longest chain 6
polynomial (31): buckets [0 1 3 0 2 2 3]
  used 5 of 7, collisions 6, longest chain 3
polyHash matches String.hashCode(): true

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

Windows PowerShell does not understand <:

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