Hash maps and collisions
A map associates a key with a value. Hashing narrows the search to a bucket. Compare keys inside the bucket to handle collisions.
Simple example
Store keys 12 and 22 with values 4 and 7. Both keys end in 2. Find 22 by checking the full key and print its value.
const std = @import("std");
fn show(value: i64) !void {
var buffer: [64]u8 = undefined;
var writer = std.fs.File.stdout().writer(&buffer);
try writer.interface.print("{d}\n", .{value});
try writer.interface.flush();
}
pub fn main() !void {
var heads = [_]i64{-1, -1, -1, -1, -1, -1, -1, -1, -1, -1};
const keys = [_]i64{12, 22};
const values = [_]i64{4, 7};
var following = [_]i64{-1, -1};
var i: i64 = 0;
while (i < 2) {
const bucket: i64 = @mod(keys[@intCast(i)], 10);
following[@intCast(i)] = heads[@intCast(bucket)];
heads[@intCast(bucket)] = i;
i += 1;
}
const wanted: i64 = 22;
var node: i64 = heads[@intCast(@mod(wanted, 10))];
while (node != -1) {
if (keys[@intCast(node)] == wanted) {
try show(values[@intCast(node)]);
break;
}
node = following[@intCast(node)];
}
}
7
Everyday examples
Find the correct shelf
Parcels 12 and 22 share the same last digit. Their shelves are 4 and 7. Where is parcel 22?
Use the digit to choose the bucket, then compare the entire parcel number. The matching key points to shelf 7.
Update a club contact
Member 16 has locker 3 and then moves to locker 5. What should a lookup by member 16 return?
Replace the value for the existing key. The member keeps one current locker entry.
Look up an unknown book
The desk has shelf entries for books 8 and 9. A student asks for book 7. What should the screen say?
Return a missing result. A real shelf numbered zero must remain distinguishable from a missing book.
Cost and limits
Lookup averages constant time with a suitable hash function and controlled load. If many keys collide, a chained bucket can take linear time to search.