#C213. Keyword Hash Buckets
Keyword Hash Buckets
Keyword Hash Buckets
You are given a list of keywords and a positive integer num_buckets. Your task is to distribute each keyword into one of the buckets based on a custom hash function. For a given keyword s, compute its hash h(s) using the formula:
$$h(s)=\sum_{i=0}^{|s|-1} s[i]\times 131^{(|s|-1-i)} $$where s[i]
is the ASCII value of the i
-th character in the string. Then, assign the keyword to bucket number h(s) mod num_buckets. Finally, output all buckets in order (from 0 to num_buckets-1). For each bucket, list the keywords assigned (in the order they appear in the input) separated by a single space. If a bucket has no keywords, print its header with nothing following.
Note: Use of the built-in hash functions is not permitted since they might be inconsistent between languages. You must implement the custom deterministic hash function described above.
inputFormat
The input is read from standard input and has the following format:
- The first line contains an integer
n
(the number of keywords). - The next
n
lines each contain a single keyword (a non-empty string without spaces). - The last line contains an integer
num_buckets
(the number of buckets).
outputFormat
For each bucket index from 0
to num_buckets - 1
, output a line in the following format:
Bucket i: keyword1 keyword2 ...
If a bucket is empty, just output Bucket i:
(with nothing after the colon). The output is written to standard output.
9
python
java
c++
javascript
rust
go
perl
ruby
swift
3
Bucket 0: java c++ javascript
Bucket 1: rust perl swift
Bucket 2: python go ruby
</p>