This commit is contained in:
krahets
2023-02-09 22:55:29 +08:00
parent 3dcf65c61b
commit 7d86e2dd11
18 changed files with 1029 additions and 71 deletions

View File

@@ -1158,7 +1158,110 @@ $$
=== "Zig"
```zig title="array_hash_map.zig"
// 键值对 int->String
const Entry = struct {
key: usize = undefined,
val: []const u8 = undefined,
pub fn init(key: usize, val: []const u8) Entry {
return Entry {
.key = key,
.val = val,
};
}
};
// 基于数组简易实现的哈希表
fn ArrayHashMap(comptime T: type) type {
return struct {
bucket: ?std.ArrayList(?T) = null,
mem_allocator: std.mem.Allocator = undefined,
const Self = @This();
// 构造函数
pub fn init(self: *Self, allocator: std.mem.Allocator) !void {
self.mem_allocator = allocator;
// 初始化一个长度为 100 的桶(数组)
self.bucket = std.ArrayList(?T).init(self.mem_allocator);
var i: i32 = 0;
while (i < 100) : (i += 1) {
try self.bucket.?.append(null);
}
}
// 析构函数
pub fn deinit(self: *Self) void {
if (self.bucket != null) self.bucket.?.deinit();
}
// 哈希函数
fn hashFunc(key: usize) usize {
var index = key % 100;
return index;
}
// 查询操作
pub fn get(self: *Self, key: usize) []const u8 {
var index = hashFunc(key);
var pair = self.bucket.?.items[index];
return pair.?.val;
}
// 添加操作
pub fn put(self: *Self, key: usize, val: []const u8) !void {
var pair = Entry.init(key, val);
var index = hashFunc(key);
self.bucket.?.items[index] = pair;
}
// 删除操作
pub fn remove(self: *Self, key: usize) !void {
var index = hashFunc(key);
// 置为 null ,代表删除
self.bucket.?.items[index] = null;
}
// 获取所有键值对
pub fn entrySet(self: *Self) !*std.ArrayList(T) {
var entry_set = std.ArrayList(T).init(self.mem_allocator);
for (self.bucket.?.items) |item| {
if (item == null) continue;
try entry_set.append(item.?);
}
return &entry_set;
}
// 获取所有键
pub fn keySet(self: *Self) !*std.ArrayList(usize) {
var key_set = std.ArrayList(usize).init(self.mem_allocator);
for (self.bucket.?.items) |item| {
if (item == null) continue;
try key_set.append(item.?.key);
}
return &key_set;
}
// 获取所有值
pub fn valueSet(self: *Self) !*std.ArrayList([]const u8) {
var value_set = std.ArrayList([]const u8).init(self.mem_allocator);
for (self.bucket.?.items) |item| {
if (item == null) continue;
try value_set.append(item.?.val);
}
return &value_set;
}
// 打印哈希表
pub fn print(self: *Self) !void {
var entry_set = try self.entrySet();
defer entry_set.deinit();
for (entry_set.items) |item| {
std.debug.print("{} -> {s}\n", .{item.key, item.val});
}
}
};
}
```
## 6.1.4. 哈希冲突