Back to problems
COMP2521
Hash Table: Bucket Sizes
Hash Table: count elements in each bucket
Given B buckets and the hash function hash(key) = key % B (key non-negative), insert n keys into the buckets (separate chaining). Print the final chain length of each bucket (bucket 0 to B−1).
Complete it: for each key, compute the bucket key % B and increment that bucket's count.
Pitfalls (straight from the bug lab): (1) always% Bto fit the key into[0, B); never use the key directly as an index (out of bounds). (2) The bucket iskey % B.
Input
- Line 1:
B n(buckets, number of keys). - Line 2:
nnon-negative integer keys (this line is empty whennis 0).
Output
- One line:
Bnumbers, the chain lengths of buckets 0…B−1, a space after each.
Example: input 7 6 / 8 15 22 5 3 17 -> 0 3 0 2 0 1 0 (8, 15, 22 all hash to bucket 1; 3, 17 to bucket 3; 5 to bucket 5).
Samples
stdin
7 6 8 15 22 5 3 17
expected
0 3 0 2 0 1 0
stdin
5 4 10 20 30 40
expected
4 0 0 0 0
c-dcc
14