data-structures · beginner · ~15 min

Map a hash to a bucket

Reduce a wide hash to a table index.

Challenge

Reduce a wide hash value to a hash-table bucket index.

Task

Implement int bucket_of(unsigned long hash, int nbuckets) that returns which bucket, in the range 0 .. nbuckets-1, the given hash maps to.

Input

  • hash: an unsigned long hash value.
  • nbuckets: the number of buckets in the table (nbuckets > 0).

Output

int: the bucket index in [0, nbuckets).

Example

bucket_of(177670, 10)    ->   0
bucket_of(5863208, 16)   ->   8
bucket_of(5381, 256)     ->   5

Edge cases

  • The result is always in [0, nbuckets).

Input format

hash: an unsigned long; nbuckets: bucket count (> 0).

Output format

int: bucket index in [0, nbuckets).

Constraints

Reduce with hash % nbuckets.

Starter code

int bucket_of(unsigned long hash, int nbuckets) {
    /* TODO */
    return 0;
}

Solve this exercise in the browser editor — compile and run against the test harness, no setup required.