diff --git a/zh-hant/README.md b/zh-hant/README.md
index 0e797a838..c8c79f7ce 100644
--- a/zh-hant/README.md
+++ b/zh-hant/README.md
@@ -65,6 +65,17 @@
>
> **—— 李沐,亞馬遜資深首席科學家**
+## 鳴謝
+
+
+
+
+
+
+[Warp is built for coding with multiple AI agents.](https://www.warp.dev/?utm_source=github&utm_medium=influencer&utm_campaign=hello-algo)
+
+強烈推薦 Warp 終端,高顏值 + 好用的 AI,體驗非常棒!
+
## 貢獻
> [!Important]
diff --git a/zh-hant/codes/c/chapter_greedy/max_capacity.c b/zh-hant/codes/c/chapter_greedy/max_capacity.c
index 04a68f245..2b3824434 100644
--- a/zh-hant/codes/c/chapter_greedy/max_capacity.c
+++ b/zh-hant/codes/c/chapter_greedy/max_capacity.c
@@ -12,7 +12,7 @@ int myMin(int a, int b) {
}
/* 求最大值 */
int myMax(int a, int b) {
- return a < b ? a : b;
+ return a > b ? a : b;
}
/* 最大容量:貪婪 */
diff --git a/zh-hant/codes/python/chapter_hashing/array_hash_map.py b/zh-hant/codes/python/chapter_hashing/array_hash_map.py
index 1cd2ffa83..f8494b0fe 100644
--- a/zh-hant/codes/python/chapter_hashing/array_hash_map.py
+++ b/zh-hant/codes/python/chapter_hashing/array_hash_map.py
@@ -26,7 +26,7 @@ class ArrayHashMap:
index = key % 100
return index
- def get(self, key: int) -> str:
+ def get(self, key: int) -> str | None:
"""查詢操作"""
index: int = self.hash_func(key)
pair: Pair = self.buckets[index]
@@ -35,7 +35,7 @@ class ArrayHashMap:
return pair.val
def put(self, key: int, val: str):
- """新增操作"""
+ """新增和更新操作"""
pair = Pair(key, val)
index: int = self.hash_func(key)
self.buckets[index] = pair
diff --git a/zh-hant/codes/rust/chapter_graph/graph_adjacency_list.rs b/zh-hant/codes/rust/chapter_graph/graph_adjacency_list.rs
index c06e5fae9..c62bbe7fe 100644
--- a/zh-hant/codes/rust/chapter_graph/graph_adjacency_list.rs
+++ b/zh-hant/codes/rust/chapter_graph/graph_adjacency_list.rs
@@ -11,7 +11,7 @@ use std::collections::HashMap;
/* 基於鄰接表實現的無向圖型別 */
pub struct GraphAdjList {
// 鄰接表,key:頂點,value:該頂點的所有鄰接頂點
- pub adj_list: HashMap
>,
+ pub adj_list: HashMap>, // maybe HashSet for value part is better?
}
impl GraphAdjList {
@@ -38,31 +38,27 @@ impl GraphAdjList {
/* 新增邊 */
pub fn add_edge(&mut self, vet1: Vertex, vet2: Vertex) {
- if !self.adj_list.contains_key(&vet1) || !self.adj_list.contains_key(&vet2) || vet1 == vet2
- {
+ if vet1 == vet2 {
panic!("value error");
}
// 新增邊 vet1 - vet2
- self.adj_list.get_mut(&vet1).unwrap().push(vet2);
- self.adj_list.get_mut(&vet2).unwrap().push(vet1);
+ self.adj_list.entry(vet1).or_default().push(vet2);
+ self.adj_list.entry(vet2).or_default().push(vet1);
}
/* 刪除邊 */
#[allow(unused)]
pub fn remove_edge(&mut self, vet1: Vertex, vet2: Vertex) {
- if !self.adj_list.contains_key(&vet1) || !self.adj_list.contains_key(&vet2) || vet1 == vet2
- {
+ if vet1 == vet2 {
panic!("value error");
}
// 刪除邊 vet1 - vet2
self.adj_list
- .get_mut(&vet1)
- .unwrap()
- .retain(|&vet| vet != vet2);
+ .entry(vet1)
+ .and_modify(|v| v.retain(|&e| e != vet2));
self.adj_list
- .get_mut(&vet2)
- .unwrap()
- .retain(|&vet| vet != vet1);
+ .entry(vet2)
+ .and_modify(|v| v.retain(|&e| e != vet1));
}
/* 新增頂點 */
@@ -77,9 +73,6 @@ impl GraphAdjList {
/* 刪除頂點 */
#[allow(unused)]
pub fn remove_vertex(&mut self, vet: Vertex) {
- if !self.adj_list.contains_key(&vet) {
- panic!("value error");
- }
// 在鄰接表中刪除頂點 vet 對應的鏈結串列
self.adj_list.remove(&vet);
// 走訪其他頂點的鏈結串列,刪除所有包含 vet 的邊
diff --git a/zh-hant/codes/rust/chapter_graph/graph_adjacency_matrix.rs b/zh-hant/codes/rust/chapter_graph/graph_adjacency_matrix.rs
index f95d4f989..ad00492c7 100644
--- a/zh-hant/codes/rust/chapter_graph/graph_adjacency_matrix.rs
+++ b/zh-hant/codes/rust/chapter_graph/graph_adjacency_matrix.rs
@@ -45,7 +45,7 @@ impl GraphAdjMat {
// 在鄰接矩陣中新增一行
self.adj_mat.push(vec![0; n]);
// 在鄰接矩陣中新增一列
- for row in &mut self.adj_mat {
+ for row in self.adj_mat.iter_mut() {
row.push(0);
}
}
@@ -60,7 +60,7 @@ impl GraphAdjMat {
// 在鄰接矩陣中刪除索引 index 的行
self.adj_mat.remove(index);
// 在鄰接矩陣中刪除索引 index 的列
- for row in &mut self.adj_mat {
+ for row in self.adj_mat.iter_mut() {
row.remove(index);
}
}
diff --git a/zh-hant/codes/rust/chapter_graph/graph_bfs.rs b/zh-hant/codes/rust/chapter_graph/graph_bfs.rs
index 4c0fbccfd..802576c70 100644
--- a/zh-hant/codes/rust/chapter_graph/graph_bfs.rs
+++ b/zh-hant/codes/rust/chapter_graph/graph_bfs.rs
@@ -22,8 +22,7 @@ fn graph_bfs(graph: GraphAdjList, start_vet: Vertex) -> Vec {
let mut que = VecDeque::new();
que.push_back(start_vet);
// 以頂點 vet 為起點,迴圈直至訪問完所有頂點
- while !que.is_empty() {
- let vet = que.pop_front().unwrap(); // 佇列首頂點出隊
+ while let Some(vet) = que.pop_front() {
res.push(vet); // 記錄訪問頂點
// 走訪該頂點的所有鄰接頂點
diff --git a/zh-hant/codes/zig/build.zig b/zh-hant/codes/zig/build.zig
index 080f84166..412804106 100644
--- a/zh-hant/codes/zig/build.zig
+++ b/zh-hant/codes/zig/build.zig
@@ -1,221 +1,169 @@
// File: build.zig
// Created Time: 2023-01-07
-// Author: codingonion (coderonion@gmail.com)
+// Author: codingonion (coderonion@gmail.com), CreatorMetaSky (creator_meta_sky@163.com)
+
+//! Zig Version: 0.14.1
+//! Build Command: zig build
+//! Run Command: zig build run | zig build run_*
+//! Test Command: zig build test | zig build test -Dtest-filter=*
const std = @import("std");
-// Zig Version: 0.11.0
-// Zig Build Command: zig build -Doptimize=ReleaseSafe
-// Zig Run Command: zig build run_* -Doptimize=ReleaseSafe
pub fn build(b: *std.Build) void {
const target = b.standardTargetOptions(.{});
const optimize = b.standardOptimizeOption(.{});
- const group_name_path = .{
- // Source File: "chapter_computational_complexity/time_complexity.zig"
- // Run Command: zig build run_time_complexity -Doptimize=ReleaseSafe
- .{ .name = "time_complexity", .path = "chapter_computational_complexity/time_complexity.zig" },
-
- // Source File: "chapter_computational_complexity/worst_best_time_complexity.zig"
- // Run Command: zig build run_worst_best_time_complexity -Doptimize=ReleaseSafe
- .{ .name = "worst_best_time_complexity", .path = "chapter_computational_complexity/worst_best_time_complexity.zig" },
-
- // Source File: "chapter_computational_complexity/space_complexity.zig"
- // Run Command: zig build run_space_complexity -Doptimize=ReleaseSafe
- .{ .name = "space_complexity", .path = "chapter_computational_complexity/space_complexity.zig" },
-
- // Source File: "chapter_computational_complexity/iteration.zig"
- // Run Command: zig build run_iteration -Doptimize=ReleaseFast
- .{ .name = "iteration", .path = "chapter_computational_complexity/iteration.zig" },
-
- // Source File: "chapter_computational_complexity/recursion.zig"
- // Run Command: zig build run_recursion -Doptimize=ReleaseFast
- .{ .name = "recursion", .path = "chapter_computational_complexity/recursion.zig" },
-
- // Source File: "chapter_array_and_linkedlist/array.zig"
- // Run Command: zig build run_array -Doptimize=ReleaseSafe
- .{ .name = "array", .path = "chapter_array_and_linkedlist/array.zig" },
-
- // Source File: "chapter_array_and_linkedlist/linked_list.zig"
- // Run Command: zig build run_linked_list -Doptimize=ReleaseSafe
- .{ .name = "linked_list", .path = "chapter_array_and_linkedlist/linked_list.zig" },
-
- // Source File: "chapter_array_and_linkedlist/list.zig"
- // Run Command: zig build run_list -Doptimize=ReleaseSafe
- .{ .name = "list", .path = "chapter_array_and_linkedlist/list.zig" },
-
- // Source File: "chapter_array_and_linkedlist/my_list.zig"
- // Run Command: zig build run_my_list -Doptimize=ReleaseSafe
- .{ .name = "my_list", .path = "chapter_array_and_linkedlist/my_list.zig" },
-
- // Source File: "chapter_stack_and_queue/stack.zig"
- // Run Command: zig build run_stack -Doptimize=ReleaseSafe
- .{ .name = "stack", .path = "chapter_stack_and_queue/stack.zig" },
-
- // Source File: "chapter_stack_and_queue/linkedlist_stack.zig"
- // Run Command: zig build run_linkedlist_stack -Doptimize=ReleaseSafe
- .{ .name = "linkedlist_stack", .path = "chapter_stack_and_queue/linkedlist_stack.zig" },
-
- // Source File: "chapter_stack_and_queue/array_stack.zig"
- // Run Command: zig build run_array_stack -Doptimize=ReleaseSafe
- .{ .name = "array_stack", .path = "chapter_stack_and_queue/array_stack.zig" },
-
- // Source File: "chapter_stack_and_queue/queue.zig"
- // Run Command: zig build run_queue -Doptimize=ReleaseSafe
- .{ .name = "queue", .path = "chapter_stack_and_queue/queue.zig" },
-
- // Source File: "chapter_stack_and_queue/array_queue.zig"
- // Run Command: zig build run_array_queue -Doptimize=ReleaseSafe
- .{ .name = "array_queue", .path = "chapter_stack_and_queue/array_queue.zig" },
-
- // Source File: "chapter_stack_and_queue/linkedlist_queue.zig"
- // Run Command: zig build run_linkedlist_queue -Doptimize=ReleaseSafe
- .{ .name = "linkedlist_queue", .path = "chapter_stack_and_queue/linkedlist_queue.zig" },
-
- // Source File: "chapter_stack_and_queue/deque.zig"
- // Run Command: zig build run_deque -Doptimize=ReleaseSafe
- .{ .name = "deque", .path = "chapter_stack_and_queue/deque.zig" },
-
- // Source File: "chapter_stack_and_queue/linkedlist_deque.zig"
- // Run Command: zig build run_linkedlist_deque -Doptimize=ReleaseSafe
- .{ .name = "linkedlist_deque", .path = "chapter_stack_and_queue/linkedlist_deque.zig" },
-
- // Source File: "chapter_hashing/hash_map.zig"
- // Run Command: zig build run_hash_map -Doptimize=ReleaseSafe
- .{ .name = "hash_map", .path = "chapter_hashing/hash_map.zig" },
-
- // Source File: "chapter_hashing/array_hash_map.zig"
- // Run Command: zig build run_array_hash_map -Doptimize=ReleaseSafe
- .{ .name = "array_hash_map", .path = "chapter_hashing/array_hash_map.zig" },
-
- // Source File: "chapter_tree/binary_tree.zig"
- // Run Command: zig build run_binary_tree -Doptimize=ReleaseSafe
- .{ .name = "binary_tree", .path = "chapter_tree/binary_tree.zig" },
-
- // Source File: "chapter_tree/binary_tree_bfs.zig"
- // Run Command: zig build run_binary_tree_bfs -Doptimize=ReleaseSafe
- .{ .name = "binary_tree_bfs", .path = "chapter_tree/binary_tree_bfs.zig" },
-
- // Source File: "chapter_tree/binary_tree_dfs.zig"
- // Run Command: zig build run_binary_tree_dfs -Doptimize=ReleaseSafe
- .{ .name = "binary_tree_dfs", .path = "chapter_tree/binary_tree_dfs.zig" },
-
- // Source File: "chapter_tree/binary_search_tree.zig"
- // Run Command: zig build run_binary_search_tree -Doptimize=ReleaseSafe
- .{ .name = "binary_search_tree", .path = "chapter_tree/binary_search_tree.zig" },
-
- // Source File: "chapter_tree/avl_tree.zig"
- // Run Command: zig build run_avl_tree -Doptimize=ReleaseSafe
- .{ .name = "avl_tree", .path = "chapter_tree/avl_tree.zig" },
-
- // Source File: "chapter_heap/heap.zig"
- // Run Command: zig build run_heap -Doptimize=ReleaseSafe
- .{ .name = "heap", .path = "chapter_heap/heap.zig" },
-
- // Source File: "chapter_heap/my_heap.zig"
- // Run Command: zig build run_my_heap -Doptimize=ReleaseSafe
- .{ .name = "my_heap", .path = "chapter_heap/my_heap.zig" },
-
- // Source File: "chapter_searching/linear_search.zig"
- // Run Command: zig build run_linear_search -Doptimize=ReleaseSafe
- .{ .name = "linear_search", .path = "chapter_searching/linear_search.zig" },
-
- // Source File: "chapter_searching/binary_search.zig"
- // Run Command: zig build run_binary_search -Doptimize=ReleaseSafe
- .{ .name = "binary_search", .path = "chapter_searching/binary_search.zig" },
-
- // Source File: "chapter_searching/hashing_search.zig"
- // Run Command: zig build run_hashing_search -Doptimize=ReleaseSafe
- .{ .name = "hashing_search", .path = "chapter_searching/hashing_search.zig" },
-
- // Source File: "chapter_searching/two_sum.zig"
- // Run Command: zig build run_two_sum -Doptimize=ReleaseSafe
- .{ .name = "two_sum", .path = "chapter_searching/two_sum.zig" },
-
- // Source File: "chapter_sorting/bubble_sort.zig"
- // Run Command: zig build run_bubble_sort -Doptimize=ReleaseSafe
- .{ .name = "bubble_sort", .path = "chapter_sorting/bubble_sort.zig" },
-
- // Source File: "chapter_sorting/insertion_sort.zig"
- // Run Command: zig build run_insertion_sort -Doptimize=ReleaseSafe
- .{ .name = "insertion_sort", .path = "chapter_sorting/insertion_sort.zig" },
-
- // Source File: "chapter_sorting/quick_sort.zig"
- // Run Command: zig build run_quick_sort -Doptimize=ReleaseSafe
- .{ .name = "quick_sort", .path = "chapter_sorting/quick_sort.zig" },
-
- // Source File: "chapter_sorting/merge_sort.zig"
- // Run Command: zig build run_merge_sort -Doptimize=ReleaseSafe
- .{ .name = "merge_sort", .path = "chapter_sorting/merge_sort.zig" },
-
- // Source File: "chapter_sorting/radix_sort.zig"
- // Run Command: zig build run_radix_sort -Doptimize=ReleaseSafe
- .{ .name = "radix_sort", .path = "chapter_sorting/radix_sort.zig" },
-
- // Source File: "chapter_dynamic_programming/climbing_stairs_backtrack.zig"
- // Run Command: zig build run_climbing_stairs_backtrack -Doptimize=ReleaseSafe
- .{ .name = "climbing_stairs_backtrack", .path = "chapter_dynamic_programming/climbing_stairs_backtrack.zig" },
-
- // Source File: "chapter_dynamic_programming/climbing_stairs_constraint_dp.zig"
- // Run Command: zig build run_climbing_stairs_constraint_dp -Doptimize=ReleaseSafe
- .{ .name = "climbing_stairs_constraint_dp", .path = "chapter_dynamic_programming/climbing_stairs_constraint_dp.zig" },
-
- // Source File: "chapter_dynamic_programming/climbing_stairs_dfs_mem.zig"
- // Run Command: zig build run_climbing_stairs_dfs_mem -Doptimize=ReleaseSafe
- .{ .name = "climbing_stairs_dfs_mem", .path = "chapter_dynamic_programming/climbing_stairs_dfs_mem.zig" },
-
- // Source File: "chapter_dynamic_programming/climbing_stairs_dfs.zig"
- // Run Command: zig build run_climbing_stairs_dfs -Doptimize=ReleaseSafe
- .{ .name = "climbing_stairs_dfs", .path = "chapter_dynamic_programming/climbing_stairs_dfs.zig" },
-
- // Source File: "chapter_dynamic_programming/climbing_stairs_dp.zig"
- // Run Command: zig build run_climbing_stairs_dp -Doptimize=ReleaseSafe
- .{ .name = "climbing_stairs_dp", .path = "chapter_dynamic_programming/climbing_stairs_dp.zig" },
-
- // Source File: "chapter_dynamic_programming/coin_change_ii.zig"
- // Run Command: zig build run_coin_change_ii -Doptimize=ReleaseSafe
- .{ .name = "coin_change_ii", .path = "chapter_dynamic_programming/coin_change_ii.zig" },
-
- // Source File: "chapter_dynamic_programming/coin_change.zig"
- // Run Command: zig build run_coin_change -Doptimize=ReleaseSafe
- .{ .name = "coin_change", .path = "chapter_dynamic_programming/coin_change.zig" },
-
- // Source File: "chapter_dynamic_programming/edit_distance.zig"
- // Run Command: zig build run_edit_distance -Doptimize=ReleaseSafe
- .{ .name = "edit_distance", .path = "chapter_dynamic_programming/edit_distance.zig" },
-
- // Source File: "chapter_dynamic_programming/knapsack.zig"
- // Run Command: zig build run_knapsack -Doptimize=ReleaseSafe
- .{ .name = "knapsack", .path = "chapter_dynamic_programming/knapsack.zig" },
-
- // Source File: "chapter_dynamic_programming/min_cost_climbing_stairs_dp.zig"
- // Run Command: zig build run_min_cost_climbing_stairs_dp -Doptimize=ReleaseSafe
- .{ .name = "min_cost_climbing_stairs_dp", .path = "chapter_dynamic_programming/min_cost_climbing_stairs_dp.zig" },
-
- // Source File: "chapter_dynamic_programming/min_path_sum.zig"
- // Run Command: zig build run_min_path_sum -Doptimize=ReleaseSafe
- .{ .name = "min_path_sum", .path = "chapter_dynamic_programming/min_path_sum.zig" },
-
- // Source File: "chapter_dynamic_programming/unbounded_knapsack.zig"
- // Run Command: zig build run_unbounded_knapsack -Doptimize=ReleaseSafe
- .{ .name = "unbounded_knapsack", .path = "chapter_dynamic_programming/unbounded_knapsack.zig" },
+ const chapters = [_][]const u8{
+ "chapter_computational_complexity",
+ "chapter_array_and_linkedlist",
+ "chapter_stack_and_queue",
+ "chapter_hashing",
+ "chapter_tree",
+ "chapter_heap",
+ "chapter_searching",
+ "chapter_sorting",
+ "chapter_dynamic_programming",
};
- inline for (group_name_path) |name_path| {
- const exe = b.addExecutable(.{
- .name = name_path.name,
- .root_source_file = .{ .path = name_path.path },
- .target = target,
- .optimize = optimize,
- });
- exe.addModule("include", b.addModule("", .{
- .source_file = .{ .path = "include/include.zig" },
- }));
- b.installArtifact(exe);
- const run_cmd = b.addRunArtifact(exe);
- run_cmd.step.dependOn(b.getInstallStep());
- if (b.args) |args| run_cmd.addArgs(args);
- const run_step = b.step("run_" ++ name_path.name, "Run the app");
- run_step.dependOn(&run_cmd.step);
+ const test_step = b.step("test", "Run unit tests");
+ const test_filters = b.option([]const []const u8, "test-filter", "Skip tests that do not match any filter") orelse &[0][]const u8{};
+
+ buildChapterExeModules(b, target, optimize, &chapters, test_step, test_filters);
+ buildMainExeModule(b, target, optimize);
+}
+
+fn buildChapterExeModules(
+ b: *std.Build,
+ target: std.Build.ResolvedTarget,
+ optimize: std.builtin.OptimizeMode,
+ chapter_dirs: []const []const u8,
+ test_step: *std.Build.Step,
+ test_filters: []const []const u8,
+) void {
+ for (chapter_dirs) |chapter_dir_name| {
+ const chapter_dir_path = std.fs.path.join(b.allocator, &[_][]const u8{chapter_dir_name}) catch continue;
+ var chapter_dir = std.fs.cwd().openDir(chapter_dir_path, .{ .iterate = true }) catch continue;
+ defer chapter_dir.close();
+
+ var it = chapter_dir.iterate();
+ while (it.next() catch continue) |chapter_dir_entry| {
+ if (chapter_dir_entry.kind != .file or !std.mem.endsWith(u8, chapter_dir_entry.name, ".zig")) continue;
+ const exe_mod = buildExeModuleFromChapterDirEntry(b, target, optimize, chapter_dir_name, chapter_dir_entry) catch continue;
+ addTestStepToExeModule(b, test_step, exe_mod, test_filters);
+ }
}
}
+
+fn buildExeModuleFromChapterDirEntry(
+ b: *std.Build,
+ target: std.Build.ResolvedTarget,
+ optimize: std.builtin.OptimizeMode,
+ chapter_dir_name: []const u8,
+ chapter_dir_entry: std.fs.Dir.Entry,
+) !*std.Build.Module {
+ const zig_file_path = try std.fs.path.join(b.allocator, &[_][]const u8{ chapter_dir_name, chapter_dir_entry.name });
+ const zig_file_name = chapter_dir_entry.name[0 .. chapter_dir_entry.name.len - 4]; // abstract zig file name from xxx.zig
+
+ // 這裡臨時只新增陣列和鏈結串列章節部分,後續修改完後全部放開
+ const new_algo_names = [_][]const u8{
+ "array",
+ "linked_list",
+ "list",
+ "my_list",
+ "iteration",
+ "recursion",
+ "space_complexity",
+ "time_complexity",
+ "worst_best_time_complexity",
+ };
+ var can_run = false;
+ for (new_algo_names) |name| {
+ if (std.mem.eql(u8, zig_file_name, name)) {
+ can_run = true;
+ }
+ }
+ if (!can_run) {
+ return error.CanNotRunUseOldZigCodes;
+ }
+
+ // std.debug.print("now run zig file name = {s}\n", .{zig_file_name});
+
+ const exe_mod = b.createModule(.{
+ .root_source_file = b.path(zig_file_path),
+ .target = target,
+ .optimize = optimize,
+ });
+
+ const exe = b.addExecutable(.{
+ .name = zig_file_name,
+ .root_module = exe_mod,
+ });
+
+ const utils_mod = createUtilsModule(b, target, optimize);
+ exe_mod.addImport("utils", utils_mod);
+
+ b.installArtifact(exe);
+
+ const run_cmd = b.addRunArtifact(exe);
+ run_cmd.step.dependOn(b.getInstallStep());
+ if (b.args) |args| {
+ run_cmd.addArgs(args);
+ }
+
+ const step_name = try std.fmt.allocPrint(b.allocator, "run_{s}", .{zig_file_name});
+ const step_desc = try std.fmt.allocPrint(b.allocator, "Run {s}/{s}.zig", .{ chapter_dir_name, zig_file_name });
+ const run_step = b.step(step_name, step_desc);
+ run_step.dependOn(&run_cmd.step);
+
+ return exe_mod;
+}
+
+fn buildMainExeModule(
+ b: *std.Build,
+ target: std.Build.ResolvedTarget,
+ optimize: std.builtin.OptimizeMode,
+) void {
+ const exe_mod = b.createModule(.{
+ .root_source_file = b.path("main.zig"),
+ .target = target,
+ .optimize = optimize,
+ });
+
+ const utils_mod = createUtilsModule(b, target, optimize);
+ exe_mod.addImport("utils", utils_mod);
+
+ const exe = b.addExecutable(.{
+ .name = "main",
+ .root_module = exe_mod,
+ });
+
+ b.installArtifact(exe);
+
+ const run_cmd = b.addRunArtifact(exe);
+ run_cmd.step.dependOn(b.getInstallStep());
+ if (b.args) |args| {
+ run_cmd.addArgs(args);
+ }
+
+ const run_step = b.step("run", "Run all hello algo zig");
+ run_step.dependOn(&run_cmd.step);
+}
+
+fn createUtilsModule(b: *std.Build, target: std.Build.ResolvedTarget, optimize: std.builtin.OptimizeMode) *std.Build.Module {
+ const utils_mod = b.createModule(.{
+ .root_source_file = b.path("utils/utils.zig"),
+ .target = target,
+ .optimize = optimize,
+ });
+ return utils_mod;
+}
+
+fn addTestStepToExeModule(b: *std.Build, test_step: *std.Build.Step, exe_mod: *std.Build.Module, test_filters: []const []const u8) void {
+ const exe_unit_tests = b.addTest(.{
+ .root_module = exe_mod,
+ .filters = test_filters,
+ });
+
+ const run_exe_unit_tests = b.addRunArtifact(exe_unit_tests);
+ test_step.dependOn(&run_exe_unit_tests.step);
+}
diff --git a/zh-hant/codes/zig/chapter_array_and_linkedlist/array.zig b/zh-hant/codes/zig/chapter_array_and_linkedlist/array.zig
index 25f2884dc..f58fcebd6 100644
--- a/zh-hant/codes/zig/chapter_array_and_linkedlist/array.zig
+++ b/zh-hant/codes/zig/chapter_array_and_linkedlist/array.zig
@@ -1,26 +1,28 @@
// File: array.zig
// Created Time: 2023-01-07
-// Author: codingonion (coderonion@gmail.com)
+// Author: codingonion (coderonion@gmail.com), CreatorMetaSky (creator_meta_sky@163.com)
const std = @import("std");
-const inc = @import("include");
+const utils = @import("utils");
// 隨機訪問元素
-pub fn randomAccess(nums: []i32) i32 {
+pub fn randomAccess(nums: []const i32) i32 {
// 在區間 [0, nums.len) 中隨機抽取一個整數
- var randomIndex = std.crypto.random.intRangeLessThan(usize, 0, nums.len);
+ const random_index = std.crypto.random.intRangeLessThan(usize, 0, nums.len);
// 獲取並返回隨機元素
- var randomNum = nums[randomIndex];
+ const randomNum = nums[random_index];
return randomNum;
}
// 擴展陣列長度
-pub fn extend(mem_allocator: std.mem.Allocator, nums: []i32, enlarge: usize) ![]i32 {
+pub fn extend(allocator: std.mem.Allocator, nums: []const i32, enlarge: usize) ![]i32 {
// 初始化一個擴展長度後的陣列
- var res = try mem_allocator.alloc(i32, nums.len + enlarge);
+ const res = try allocator.alloc(i32, nums.len + enlarge);
@memset(res, 0);
+
// 將原陣列中的所有元素複製到新陣列
- std.mem.copy(i32, res, nums);
+ std.mem.copyForwards(i32, res, nums);
+
// 返回擴展後的新陣列
return res;
}
@@ -46,18 +48,26 @@ pub fn remove(nums: []i32, index: usize) void {
}
// 走訪陣列
-pub fn traverse(nums: []i32) void {
+pub fn traverse(nums: []const i32) void {
var count: i32 = 0;
+
// 透過索引走訪陣列
- var i: i32 = 0;
+ var i: usize = 0;
while (i < nums.len) : (i += 1) {
count += nums[i];
}
- count = 0;
+
// 直接走訪陣列元素
+ count = 0;
for (nums) |num| {
count += num;
}
+
+ // 同時走訪資料索引和元素
+ for (nums, 0..) |num, index| {
+ count += nums[index];
+ count += num;
+ }
}
// 在陣列中查詢指定元素
@@ -69,49 +79,53 @@ pub fn find(nums: []i32, target: i32) i32 {
}
// Driver Code
-pub fn main() !void {
- // 初始化記憶體分配器
- var mem_arena = std.heap.ArenaAllocator.init(std.heap.page_allocator);
- defer mem_arena.deinit();
- const mem_allocator = mem_arena.allocator();
-
+pub fn run() !void {
// 初始化陣列
- var arr = [_]i32{0} ** 5;
- std.debug.print("陣列 arr = ", .{});
- inc.PrintUtil.printArray(i32, &arr);
+ const arr = [_]i32{0} ** 5;
+ std.debug.print("陣列 arr = {}\n", .{utils.fmt.slice(&arr)});
+ // 陣列切片
var array = [_]i32{ 1, 3, 2, 5, 4 };
var known_at_runtime_zero: usize = 0;
- var nums = array[known_at_runtime_zero..];
- std.debug.print("\n陣列 nums = ", .{});
- inc.PrintUtil.printArray(i32, nums);
+ _ = &known_at_runtime_zero;
+ var nums = array[known_at_runtime_zero..array.len]; // 透過 known_at_runtime_zero 執行時變數將指標變切片
+ std.debug.print("陣列 nums = {}\n", .{utils.fmt.slice(nums)});
// 隨機訪問
- var randomNum = randomAccess(nums);
- std.debug.print("\n在 nums 中獲取隨機元素 {}", .{randomNum});
+ const randomNum = randomAccess(nums);
+ std.debug.print("在 nums 中獲取隨機元素 {}\n", .{randomNum});
+
+ // 初始化記憶體分配器
+ var arena = std.heap.ArenaAllocator.init(std.heap.page_allocator);
+ defer arena.deinit();
+ const allocator = arena.allocator();
// 長度擴展
- nums = try extend(mem_allocator, nums, 3);
- std.debug.print("\n將陣列長度擴展至 8 ,得到 nums = ", .{});
- inc.PrintUtil.printArray(i32, nums);
+ nums = try extend(allocator, nums, 3);
+ std.debug.print("將陣列長度擴展至 8 ,得到 nums = {}\n", .{utils.fmt.slice(nums)});
// 插入元素
insert(nums, 6, 3);
- std.debug.print("\n在索引 3 處插入數字 6 ,得到 nums = ", .{});
- inc.PrintUtil.printArray(i32, nums);
+ std.debug.print("在索引 3 處插入數字 6 ,得到 nums = {}\n", .{utils.fmt.slice(nums)});
// 刪除元素
remove(nums, 2);
- std.debug.print("\n刪除索引 2 處的元素,得到 nums = ", .{});
- inc.PrintUtil.printArray(i32, nums);
+ std.debug.print("刪除索引 2 處的元素,得到 nums = {}\n", .{utils.fmt.slice(nums)});
// 走訪陣列
traverse(nums);
// 查詢元素
- var index = find(nums, 3);
- std.debug.print("\n在 nums 中查詢元素 3 ,得到索引 = {}\n", .{index});
+ const index = find(nums, 3);
+ std.debug.print("在 nums 中查詢元素 3 ,得到索引 = {}\n", .{index});
- _ = try std.io.getStdIn().reader().readByte();
+ std.debug.print("\n", .{});
}
+pub fn main() !void {
+ try run();
+}
+
+test "array" {
+ try run();
+}
diff --git a/zh-hant/codes/zig/chapter_array_and_linkedlist/linked_list.zig b/zh-hant/codes/zig/chapter_array_and_linkedlist/linked_list.zig
index 2e255f10b..b55a3a860 100644
--- a/zh-hant/codes/zig/chapter_array_and_linkedlist/linked_list.zig
+++ b/zh-hant/codes/zig/chapter_array_and_linkedlist/linked_list.zig
@@ -1,84 +1,106 @@
// File: linked_list.zig
// Created Time: 2023-01-07
-// Author: codingonion (coderonion@gmail.com)
+// Author: codingonion (coderonion@gmail.com), CreatorMetaSky (creator_meta_sky@163.com)
const std = @import("std");
-const inc = @import("include");
+const utils = @import("utils");
+const ListNode = utils.ListNode;
// 在鏈結串列的節點 n0 之後插入節點 P
-pub fn insert(n0: ?*inc.ListNode(i32), P: ?*inc.ListNode(i32)) void {
- var n1 = n0.?.next;
- P.?.next = n1;
- n0.?.next = P;
+pub fn insert(comptime T: type, n0: *ListNode(T), P: *ListNode(T)) void {
+ const n1 = n0.next;
+ P.next = n1;
+ n0.next = P;
}
// 刪除鏈結串列的節點 n0 之後的首個節點
-pub fn remove(n0: ?*inc.ListNode(i32)) void {
- if (n0.?.next == null) return;
- // n0 -> P -> n1
- var P = n0.?.next;
- var n1 = P.?.next;
- n0.?.next = n1;
+pub fn remove(comptime T: type, n0: *ListNode(T)) void {
+ // n0 -> P -> n1 => n0 -> n1
+ const P = n0.next;
+ const n1 = P.?.next;
+ n0.next = n1;
}
// 訪問鏈結串列中索引為 index 的節點
-pub fn access(node: ?*inc.ListNode(i32), index: i32) ?*inc.ListNode(i32) {
- var head = node;
+pub fn access(comptime T: type, node: *ListNode(T), index: i32) ?*ListNode(T) {
+ var head: ?*ListNode(T) = node;
var i: i32 = 0;
while (i < index) : (i += 1) {
- head = head.?.next;
- if (head == null) return null;
+ if (head) |cur| {
+ head = cur.next;
+ } else {
+ return null;
+ }
}
return head;
}
// 在鏈結串列中查詢值為 target 的首個節點
-pub fn find(node: ?*inc.ListNode(i32), target: i32) i32 {
- var head = node;
+pub fn find(comptime T: type, node: *ListNode(T), target: T) i32 {
+ var head: ?*ListNode(T) = node;
var index: i32 = 0;
- while (head != null) {
- if (head.?.val == target) return index;
- head = head.?.next;
+ while (head) |cur| {
+ if (cur.val == target) return index;
+ head = cur.next;
index += 1;
}
return -1;
}
// Driver Code
-pub fn main() !void {
- // 初始化鏈結串列
- // 初始化各個節點
- var n0 = inc.ListNode(i32){.val = 1};
- var n1 = inc.ListNode(i32){.val = 3};
- var n2 = inc.ListNode(i32){.val = 2};
- var n3 = inc.ListNode(i32){.val = 5};
- var n4 = inc.ListNode(i32){.val = 4};
+pub fn run() void {
+ // 初始化各個節點
+ var n0 = ListNode(i32){ .val = 1 };
+ var n1 = ListNode(i32){ .val = 3 };
+ var n2 = ListNode(i32){ .val = 2 };
+ var n3 = ListNode(i32){ .val = 5 };
+ var n4 = ListNode(i32){ .val = 4 };
// 構建節點之間的引用
n0.next = &n1;
n1.next = &n2;
n2.next = &n3;
n3.next = &n4;
- std.debug.print("初始化的鏈結串列為", .{});
- try inc.PrintUtil.printLinkedList(i32, &n0);
+ std.debug.print(
+ "初始化的鏈結串列為 {}\n",
+ .{utils.fmt.linkedList(i32, &n0)},
+ );
// 插入節點
- var tmp = inc.ListNode(i32){.val = 0};
- insert(&n0, &tmp);
- std.debug.print("插入節點後的鏈結串列為", .{});
- try inc.PrintUtil.printLinkedList(i32, &n0);
+ var tmp = ListNode(i32){ .val = 0 };
+ insert(i32, &n0, &tmp);
+ std.debug.print(
+ "插入節點後的鏈結串列為 {}\n",
+ .{utils.fmt.linkedList(i32, &n0)},
+ );
// 刪除節點
- remove(&n0);
- std.debug.print("刪除節點後的鏈結串列為", .{});
- try inc.PrintUtil.printLinkedList(i32, &n0);
+ remove(i32, &n0);
+ std.debug.print(
+ "刪除節點後的鏈結串列為{}\n",
+ .{utils.fmt.linkedList(i32, &n0)},
+ );
// 訪問節點
- var node = access(&n0, 3);
- std.debug.print("鏈結串列中索引 3 處的節點的值 = {}\n", .{node.?.val});
+ const node = access(i32, &n0, 3);
+ std.debug.print(
+ "鏈結串列中索引 3 處的節點的值 = {}\n",
+ .{node.?.val},
+ );
// 查詢節點
- var index = find(&n0, 2);
- std.debug.print("鏈結串列中值為 2 的節點的索引 = {}\n", .{index});
+ const index = find(i32, &n0, 2);
+ std.debug.print(
+ "鏈結串列中值為 2 的節點的索引 = {}\n",
+ .{index},
+ );
- _ = try std.io.getStdIn().reader().readByte();
-}
\ No newline at end of file
+ std.debug.print("\n", .{});
+}
+
+pub fn main() void {
+ run();
+}
+
+test "linked_list" {
+ run();
+}
diff --git a/zh-hant/codes/zig/chapter_array_and_linkedlist/list.zig b/zh-hant/codes/zig/chapter_array_and_linkedlist/list.zig
index 6e2b1401e..f55bdd2bc 100644
--- a/zh-hant/codes/zig/chapter_array_and_linkedlist/list.zig
+++ b/zh-hant/codes/zig/chapter_array_and_linkedlist/list.zig
@@ -1,33 +1,30 @@
// File: list.zig
// Created Time: 2023-01-07
-// Author: codingonion (coderonion@gmail.com)
+// Author: codingonion (coderonion@gmail.com), CreatorMetaSky (creator_meta_sky@163.com)
const std = @import("std");
-const inc = @import("include");
+const utils = @import("utils");
// Driver Code
-pub fn main() !void {
+pub fn run() !void {
// 初始化串列
var nums = std.ArrayList(i32).init(std.heap.page_allocator);
- // 延遲釋放記憶體
- defer nums.deinit();
+ defer nums.deinit(); // 延遲釋放記憶體
+
try nums.appendSlice(&[_]i32{ 1, 3, 2, 5, 4 });
- std.debug.print("串列 nums = ", .{});
- inc.PrintUtil.printList(i32, nums);
+ std.debug.print("串列 nums = {}\n", .{utils.fmt.slice(nums.items)});
// 訪問元素
- var num = nums.items[1];
- std.debug.print("\n訪問索引 1 處的元素,得到 num = {}", .{num});
+ const num = nums.items[1];
+ std.debug.print("訪問索引 1 處的元素,得到 num = {}\n", .{num});
// 更新元素
nums.items[1] = 0;
- std.debug.print("\n將索引 1 處的元素更新為 0 ,得到 nums = ", .{});
- inc.PrintUtil.printList(i32, nums);
+ std.debug.print("將索引 1 處的元素更新為 0 ,得到 nums = {}\n", .{utils.fmt.slice(nums.items)});
// 清空串列
nums.clearRetainingCapacity();
- std.debug.print("\n清空串列後 nums = ", .{});
- inc.PrintUtil.printList(i32, nums);
+ std.debug.print("清空串列後 nums = {}\n", .{utils.fmt.slice(nums.items)});
// 在尾部新增元素
try nums.append(1);
@@ -35,25 +32,23 @@ pub fn main() !void {
try nums.append(2);
try nums.append(5);
try nums.append(4);
- std.debug.print("\n新增元素後 nums = ", .{});
- inc.PrintUtil.printList(i32, nums);
+ std.debug.print("新增元素後 nums = {}\n", .{utils.fmt.slice(nums.items)});
// 在中間插入元素
try nums.insert(3, 6);
- std.debug.print("\n在索引 3 處插入數字 6 ,得到 nums = ", .{});
- inc.PrintUtil.printList(i32, nums);
+ std.debug.print("在索引 3 處插入數字 6 ,得到 nums = {}\n", .{utils.fmt.slice(nums.items)});
// 刪除元素
_ = nums.orderedRemove(3);
- std.debug.print("\n刪除索引 3 處的元素,得到 nums = ", .{});
- inc.PrintUtil.printList(i32, nums);
+ std.debug.print("刪除索引 3 處的元素,得到 nums = {}\n", .{utils.fmt.slice(nums.items)});
// 透過索引走訪串列
var count: i32 = 0;
- var i: i32 = 0;
+ var i: usize = 0;
while (i < nums.items.len) : (i += 1) {
- count += nums[i];
+ count += nums.items[i];
}
+
// 直接走訪串列元素
count = 0;
for (nums.items) |x| {
@@ -65,14 +60,19 @@ pub fn main() !void {
defer nums1.deinit();
try nums1.appendSlice(&[_]i32{ 6, 8, 7, 10, 9 });
try nums.insertSlice(nums.items.len, nums1.items);
- std.debug.print("\n將串列 nums1 拼接到 nums 之後,得到 nums = ", .{});
- inc.PrintUtil.printList(i32, nums);
+ std.debug.print("將串列 nums1 拼接到 nums 之後,得到 nums = {}\n", .{utils.fmt.slice(nums.items)});
// 排序串列
std.mem.sort(i32, nums.items, {}, comptime std.sort.asc(i32));
- std.debug.print("\n排序串列後 nums = ", .{});
- inc.PrintUtil.printList(i32, nums);
+ std.debug.print("排序串列後 nums = {}\n", .{utils.fmt.slice(nums.items)});
- _ = try std.io.getStdIn().reader().readByte();
+ std.debug.print("\n", .{});
}
+pub fn main() !void {
+ try run();
+}
+
+test "list" {
+ try run();
+}
diff --git a/zh-hant/codes/zig/chapter_array_and_linkedlist/my_list.zig b/zh-hant/codes/zig/chapter_array_and_linkedlist/my_list.zig
index 1e38998db..0d13a3f27 100644
--- a/zh-hant/codes/zig/chapter_array_and_linkedlist/my_list.zig
+++ b/zh-hant/codes/zig/chapter_array_and_linkedlist/my_list.zig
@@ -1,132 +1,171 @@
// File: my_list.zig
// Created Time: 2023-01-08
-// Author: codingonion (coderonion@gmail.com)
+// Author: codingonion (coderonion@gmail.com), CreatorMetaSky (creator_meta_sky@163.com)
const std = @import("std");
-const inc = @import("include");
+const utils = @import("utils");
// 串列類別
-pub fn MyList(comptime T: type) type {
- return struct {
- const Self = @This();
-
- arr: []T = undefined, // 陣列(儲存串列元素)
- arrCapacity: usize = 10, // 串列容量
- numSize: usize = 0, // 串列長度(當前元素數量)
- extendRatio: usize = 2, // 每次串列擴容的倍數
- mem_arena: ?std.heap.ArenaAllocator = null,
- mem_allocator: std.mem.Allocator = undefined, // 記憶體分配器
+const MyList = struct {
+ const Self = @This();
- // 建構子(分配記憶體+初始化串列)
- pub fn init(self: *Self, allocator: std.mem.Allocator) !void {
- if (self.mem_arena == null) {
- self.mem_arena = std.heap.ArenaAllocator.init(allocator);
- self.mem_allocator = self.mem_arena.?.allocator();
- }
- self.arr = try self.mem_allocator.alloc(T, self.arrCapacity);
- @memset(self.arr, @as(T, 0));
- }
+ items: []i32, // 陣列(儲存串列元素)
+ capacity: usize, // 串列容量
+ allocator: std.mem.Allocator, // 記憶體分配器
- // 析構函式(釋放記憶體)
- pub fn deinit(self: *Self) void {
- if (self.mem_arena == null) return;
- self.mem_arena.?.deinit();
- }
+ extend_ratio: usize = 2, // 每次串列擴容的倍數
- // 獲取串列長度(當前元素數量)
- pub fn size(self: *Self) usize {
- return self.numSize;
- }
+ // 建構子(分配記憶體+初始化串列)
+ pub fn init(allocator: std.mem.Allocator) Self {
+ return Self{
+ .items = &[_]i32{},
+ .capacity = 0,
+ .allocator = allocator,
+ };
+ }
- // 獲取串列容量
- pub fn capacity(self: *Self) usize {
- return self.arrCapacity;
- }
+ // 析構函式(釋放記憶體)
+ pub fn deinit(self: Self) void {
+ self.allocator.free(self.allocatedSlice());
+ }
- // 訪問元素
- pub fn get(self: *Self, index: usize) T {
- // 索引如果越界,則丟擲異常,下同
- if (index < 0 or index >= self.size()) @panic("索引越界");
- return self.arr[index];
- }
+ // 在尾部新增元素
+ pub fn add(self: *Self, item: i32) !void {
+ // 元素數量超出容量時,觸發擴容機制
+ const newlen = self.items.len + 1;
+ try self.ensureTotalCapacity(newlen);
// 更新元素
- pub fn set(self: *Self, index: usize, num: T) void {
- // 索引如果越界,則丟擲異常,下同
- if (index < 0 or index >= self.size()) @panic("索引越界");
- self.arr[index] = num;
- }
+ self.items.len += 1;
+ const new_item_ptr = &self.items[self.items.len - 1];
+ new_item_ptr.* = item;
+ }
- // 在尾部新增元素
- pub fn add(self: *Self, num: T) !void {
- // 元素數量超出容量時,觸發擴容機制
- if (self.size() == self.capacity()) try self.extendCapacity();
- self.arr[self.size()] = num;
- // 更新元素數量
- self.numSize += 1;
- }
+ // 獲取串列長度(當前元素數量)
+ pub fn getSize(self: *Self) usize {
+ return self.items.len;
+ }
- // 在中間插入元素
- pub fn insert(self: *Self, index: usize, num: T) !void {
- if (index < 0 or index >= self.size()) @panic("索引越界");
- // 元素數量超出容量時,觸發擴容機制
- if (self.size() == self.capacity()) try self.extendCapacity();
- // 將索引 index 以及之後的元素都向後移動一位
- var j = self.size() - 1;
- while (j >= index) : (j -= 1) {
- self.arr[j + 1] = self.arr[j];
+ // 獲取串列容量
+ pub fn getCapacity(self: *Self) usize {
+ return self.capacity;
+ }
+
+ // 訪問元素
+ pub fn get(self: *Self, index: usize) i32 {
+ // 索引如果越界,則丟擲異常,下同
+ if (index < 0 or index >= self.items.len) {
+ @panic("索引越界");
+ }
+ return self.items[index];
+ }
+
+ // 更新元素
+ pub fn set(self: *Self, index: usize, num: i32) void {
+ // 索引如果越界,則丟擲異常,下同
+ if (index < 0 or index >= self.items.len) {
+ @panic("索引越界");
+ }
+ self.items[index] = num;
+ }
+
+ // 在中間插入元素
+ pub fn insert(self: *Self, index: usize, item: i32) !void {
+ if (index < 0 or index >= self.items.len) {
+ @panic("索引越界");
+ }
+
+ // 元素數量超出容量時,觸發擴容機制
+ const newlen = self.items.len + 1;
+ try self.ensureTotalCapacity(newlen);
+
+ // 將索引 index 以及之後的元素都向後移動一位
+ self.items.len += 1;
+ var i = self.items.len - 1;
+ while (i >= index) : (i -= 1) {
+ self.items[i] = self.items[i - 1];
+ }
+ self.items[index] = item;
+ }
+
+ // 刪除元素
+ pub fn remove(self: *Self, index: usize) i32 {
+ if (index < 0 or index >= self.getSize()) {
+ @panic("索引越界");
+ }
+ // 將索引 index 之後的元素都向前移動一位
+ const item = self.items[index];
+ var i = index;
+ while (i < self.items.len - 1) : (i += 1) {
+ self.items[i] = self.items[i + 1];
+ }
+ self.items.len -= 1;
+ // 返回被刪除的元素
+ return item;
+ }
+
+ // 將串列轉換為陣列
+ pub fn toArraySlice(self: *Self) ![]i32 {
+ return self.toOwnedSlice(false);
+ }
+
+ // 返回新的切片並設定是否要重置或清空串列容器
+ pub fn toOwnedSlice(self: *Self, clear: bool) ![]i32 {
+ const allocator = self.allocator;
+ const old_memory = self.allocatedSlice();
+ if (allocator.remap(old_memory, self.items.len)) |new_items| {
+ if (clear) {
+ self.* = init(allocator);
}
- self.arr[index] = num;
- // 更新元素數量
- self.numSize += 1;
+ return new_items;
}
- // 刪除元素
- pub fn remove(self: *Self, index: usize) T {
- if (index < 0 or index >= self.size()) @panic("索引越界");
- var num = self.arr[index];
- // 將索引 index 之後的元素都向前移動一位
- var j = index;
- while (j < self.size() - 1) : (j += 1) {
- self.arr[j] = self.arr[j + 1];
- }
- // 更新元素數量
- self.numSize -= 1;
- // 返回被刪除的元素
- return num;
+ const new_memory = try allocator.alloc(i32, self.items.len);
+ @memcpy(new_memory, self.items);
+ if (clear) {
+ self.clearAndFree();
}
+ return new_memory;
+ }
- // 串列擴容
- pub fn extendCapacity(self: *Self) !void {
- // 新建一個長度為 size * extendRatio 的陣列,並將原陣列複製到新陣列
- var newCapacity = self.capacity() * self.extendRatio;
- var extend = try self.mem_allocator.alloc(T, newCapacity);
- @memset(extend, @as(T, 0));
- // 將原陣列中的所有元素複製到新陣列
- std.mem.copy(T, extend, self.arr);
- self.arr = extend;
- // 更新串列容量
- self.arrCapacity = newCapacity;
- }
+ // 串列擴容
+ fn ensureTotalCapacity(self: *Self, new_capacity: usize) !void {
+ if (self.capacity >= new_capacity) return;
+ const capcacity = if (self.capacity == 0) 10 else self.capacity;
+ const better_capacity = capcacity * self.extend_ratio;
- // 將串列轉換為陣列
- pub fn toArray(self: *Self) ![]T {
- // 僅轉換有效長度範圍內的串列元素
- var arr = try self.mem_allocator.alloc(T, self.size());
- @memset(arr, @as(T, 0));
- for (arr, 0..) |*num, i| {
- num.* = self.get(i);
- }
- return arr;
+ const old_memory = self.allocatedSlice();
+ if (self.allocator.remap(old_memory, better_capacity)) |new_memory| {
+ self.items.ptr = new_memory.ptr;
+ self.capacity = new_memory.len;
+ } else {
+ const new_memory = try self.allocator.alloc(i32, better_capacity);
+ @memcpy(new_memory[0..self.items.len], self.items);
+ self.allocator.free(old_memory);
+ self.items.ptr = new_memory.ptr;
+ self.capacity = new_memory.len;
}
- };
-}
+ }
+
+ fn clearAndFree(self: *Self, allocator: std.mem.Allocator) void {
+ allocator.free(self.allocatedSlice());
+ self.items.len = 0;
+ self.capacity = 0;
+ }
+
+ fn allocatedSlice(self: Self) []i32 {
+ return self.items.ptr[0..self.capacity];
+ }
+};
// Driver Code
-pub fn main() !void {
+pub fn run() !void {
+ var gpa = std.heap.DebugAllocator(.{}){};
+ defer _ = gpa.deinit();
+ const allocator = gpa.allocator();
+
// 初始化串列
- var nums = MyList(i32){};
- try nums.init(std.heap.page_allocator);
+ var nums = MyList.init(allocator);
// 延遲釋放記憶體
defer nums.deinit();
@@ -136,28 +175,36 @@ pub fn main() !void {
try nums.add(2);
try nums.add(5);
try nums.add(4);
- std.debug.print("串列 nums = ", .{});
- inc.PrintUtil.printArray(i32, try nums.toArray());
- std.debug.print(" ,容量 = {} ,長度 = {}", .{nums.capacity(), nums.size()});
+ std.debug.print("串列 nums = {} ,容量 = {} ,長度 = {}\n", .{
+ utils.fmt.slice(nums.items),
+ nums.getCapacity(),
+ nums.getSize(),
+ });
// 在中間插入元素
try nums.insert(3, 6);
- std.debug.print("\n在索引 3 處插入數字 6 ,得到 nums = ", .{});
- inc.PrintUtil.printArray(i32, try nums.toArray());
+ std.debug.print(
+ "在索引 3 處插入數字 6 ,得到 nums = {}\n",
+ .{utils.fmt.slice(nums.items)},
+ );
// 刪除元素
_ = nums.remove(3);
- std.debug.print("\n刪除索引 3 處的元素,得到 nums = ", .{});
- inc.PrintUtil.printArray(i32, try nums.toArray());
+ std.debug.print(
+ "刪除索引 3 處的元素,得到 nums = {}\n",
+ .{utils.fmt.slice(nums.items)},
+ );
// 訪問元素
- var num = nums.get(1);
- std.debug.print("\n訪問索引 1 處的元素,得到 num = {}", .{num});
+ const num = nums.get(1);
+ std.debug.print("訪問索引 1 處的元素,得到 num = {}\n", .{num});
// 更新元素
nums.set(1, 0);
- std.debug.print("\n將索引 1 處的元素更新為 0 ,得到 nums = ", .{});
- inc.PrintUtil.printArray(i32, try nums.toArray());
+ std.debug.print(
+ "將索引 1 處的元素更新為 0 ,得到 nums = {}\n",
+ .{utils.fmt.slice(nums.items)},
+ );
// 測試擴容機制
var i: i32 = 0;
@@ -165,9 +212,22 @@ pub fn main() !void {
// 在 i = 5 時,串列長度將超出串列容量,此時觸發擴容機制
try nums.add(i);
}
- std.debug.print("\n擴容後的串列 nums = ", .{});
- inc.PrintUtil.printArray(i32, try nums.toArray());
- std.debug.print(" ,容量 = {} ,長度 = {}\n", .{nums.capacity(), nums.size()});
+ std.debug.print(
+ "擴容後的串列 nums = {} ,容量 = {} ,長度 = {}\n",
+ .{
+ utils.fmt.slice(nums.items),
+ nums.getCapacity(),
+ nums.getSize(),
+ },
+ );
- _ = try std.io.getStdIn().reader().readByte();
+ std.debug.print("\n", .{});
+}
+
+pub fn main() !void {
+ try run();
+}
+
+test "my_list" {
+ try run();
}
diff --git a/zh-hant/codes/zig/chapter_computational_complexity/iteration.zig b/zh-hant/codes/zig/chapter_computational_complexity/iteration.zig
index b458becca..ab3c8b6ca 100644
--- a/zh-hant/codes/zig/chapter_computational_complexity/iteration.zig
+++ b/zh-hant/codes/zig/chapter_computational_complexity/iteration.zig
@@ -1,6 +1,6 @@
// File: iteration.zig
// Created Time: 2023-09-27
-// Author: QiLOL (pikaqqpika@gmail.com)
+// Author: QiLOL (pikaqqpika@gmail.com), CreatorMetaSky (creator_meta_sky@163.com)
const std = @import("std");
const Allocator = std.mem.Allocator;
@@ -9,20 +9,19 @@ const Allocator = std.mem.Allocator;
fn forLoop(n: usize) i32 {
var res: i32 = 0;
// 迴圈求和 1, 2, ..., n-1, n
- for (1..n+1) |i| {
- res = res + @as(i32, @intCast(i));
+ for (1..n + 1) |i| {
+ res += @intCast(i);
}
return res;
-}
+}
// while 迴圈
fn whileLoop(n: i32) i32 {
var res: i32 = 0;
var i: i32 = 1; // 初始化條件變數
// 迴圈求和 1, 2, ..., n-1, n
- while (i <= n) {
+ while (i <= n) : (i += 1) {
res += @intCast(i);
- i += 1;
}
return res;
}
@@ -32,11 +31,12 @@ fn whileLoopII(n: i32) i32 {
var res: i32 = 0;
var i: i32 = 1; // 初始化條件變數
// 迴圈求和 1, 4, 10, ...
- while (i <= n) {
- res += @intCast(i);
+ while (i <= n) : ({
// 更新條件變數
i += 1;
i *= 2;
+ }) {
+ res += @intCast(i);
}
return res;
}
@@ -47,31 +47,45 @@ fn nestedForLoop(allocator: Allocator, n: usize) ![]const u8 {
defer res.deinit();
var buffer: [20]u8 = undefined;
// 迴圈 i = 1, 2, ..., n-1, n
- for (1..n+1) |i| {
+ for (1..n + 1) |i| {
// 迴圈 j = 1, 2, ..., n-1, n
- for (1..n+1) |j| {
- var _str = try std.fmt.bufPrint(&buffer, "({d}, {d}), ", .{i, j});
- try res.appendSlice(_str);
+ for (1..n + 1) |j| {
+ const str = try std.fmt.bufPrint(&buffer, "({d}, {d}), ", .{ i, j });
+ try res.appendSlice(str);
}
}
return res.toOwnedSlice();
}
// Driver Code
-pub fn main() !void {
+pub fn run() !void {
+ var gpa = std.heap.DebugAllocator(.{}){};
+ defer _ = gpa.deinit();
+ const allocator = gpa.allocator();
+
const n: i32 = 5;
var res: i32 = 0;
res = forLoop(n);
- std.debug.print("\nfor 迴圈的求和結果 res = {}\n", .{res});
+ std.debug.print("for 迴圈的求和結果 res = {}\n", .{res});
res = whileLoop(n);
- std.debug.print("\nwhile 迴圈的求和結果 res = {}\n", .{res});
+ std.debug.print("while 迴圈的求和結果 res = {}\n", .{res});
res = whileLoopII(n);
- std.debug.print("\nwhile 迴圈(兩次更新)求和結果 res = {}\n", .{res});
+ std.debug.print("while 迴圈(兩次更新)求和結果 res = {}\n", .{res});
- const allocator = std.heap.page_allocator;
const resStr = try nestedForLoop(allocator, n);
- std.debug.print("\n雙層 for 迴圈的走訪結果 {s}\n", .{resStr});
+ std.debug.print("雙層 for 迴圈的走訪結果 {s}\n", .{resStr});
+ allocator.free(resStr);
+
+ std.debug.print("\n", .{});
+}
+
+pub fn main() !void {
+ try run();
+}
+
+test "interation" {
+ try run();
}
diff --git a/zh-hant/codes/zig/chapter_computational_complexity/recursion.zig b/zh-hant/codes/zig/chapter_computational_complexity/recursion.zig
index de2b1d099..24e1fdc1f 100644
--- a/zh-hant/codes/zig/chapter_computational_complexity/recursion.zig
+++ b/zh-hant/codes/zig/chapter_computational_complexity/recursion.zig
@@ -1,7 +1,7 @@
// File: recursion.zig
// Created Time: 2023-09-27
-// Author: QiLOL (pikaqqpika@gmail.com)
-
+// Author: QiLOL (pikaqqpika@gmail.com), CreatorMetaSky (creator_meta_sky@163.com)
+
const std = @import("std");
// 遞迴函式
@@ -11,7 +11,7 @@ fn recur(n: i32) i32 {
return 1;
}
// 遞:遞迴呼叫
- var res: i32 = recur(n - 1);
+ const res = recur(n - 1);
// 迴:返回結果
return n + res;
}
@@ -54,25 +54,35 @@ fn fib(n: i32) i32 {
return n - 1;
}
// 遞迴呼叫 f(n) = f(n-1) + f(n-2)
- var res: i32 = fib(n - 1) + fib(n - 2);
+ const res: i32 = fib(n - 1) + fib(n - 2);
// 返回結果 f(n)
return res;
}
// Driver Code
-pub fn main() !void {
+pub fn run() void {
const n: i32 = 5;
var res: i32 = 0;
res = recur(n);
- std.debug.print("\n遞迴函式的求和結果 res = {}\n", .{recur(n)});
+ std.debug.print("遞迴函式的求和結果 res = {}\n", .{recur(n)});
res = forLoopRecur(n);
- std.debug.print("\n使用迭代模擬遞迴的求和結果 res = {}\n", .{forLoopRecur(n)});
+ std.debug.print("使用迭代模擬遞迴的求和結果 res = {}\n", .{forLoopRecur(n)});
res = tailRecur(n, 0);
- std.debug.print("\n尾遞迴函式的求和結果 res = {}\n", .{tailRecur(n, 0)});
+ std.debug.print("尾遞迴函式的求和結果 res = {}\n", .{tailRecur(n, 0)});
res = fib(n);
- std.debug.print("\n費波那契數列的第 {} 項為 {}\n", .{n, fib(n)});
+ std.debug.print("費波那契數列的第 {} 項為 {}\n", .{ n, fib(n) });
+
+ std.debug.print("\n", .{});
+}
+
+pub fn main() void {
+ run();
+}
+
+test "recursion" {
+ run();
}
diff --git a/zh-hant/codes/zig/chapter_computational_complexity/space_complexity.zig b/zh-hant/codes/zig/chapter_computational_complexity/space_complexity.zig
index 9205cc759..8774a31f3 100644
--- a/zh-hant/codes/zig/chapter_computational_complexity/space_complexity.zig
+++ b/zh-hant/codes/zig/chapter_computational_complexity/space_complexity.zig
@@ -1,9 +1,11 @@
// File: space_complexity.zig
// Created Time: 2023-01-07
-// Author: codingonion (coderonion@gmail.com)
+// Author: codingonion (coderonion@gmail.com), CreatorMetaSky (creator_meta_sky@163.com)
const std = @import("std");
-const inc = @import("include");
+const utils = @import("utils");
+const ListNode = utils.ListNode;
+const TreeNode = utils.TreeNode;
// 函式
fn function() i32 {
@@ -15,13 +17,13 @@ fn function() i32 {
fn constant(n: i32) void {
// 常數、變數、物件佔用 O(1) 空間
const a: i32 = 0;
- var b: i32 = 0;
- var nums = [_]i32{0}**10000;
- var node = inc.ListNode(i32){.val = 0};
+ const b: i32 = 0;
+ const nums = [_]i32{0} ** 10000;
+ const node = ListNode(i32){ .val = 0 };
var i: i32 = 0;
// 迴圈中的變數佔用 O(1) 空間
while (i < n) : (i += 1) {
- var c: i32 = 0;
+ const c: i32 = 0;
_ = c;
}
// 迴圈中的函式佔用 O(1) 空間
@@ -38,7 +40,7 @@ fn constant(n: i32) void {
// 線性階
fn linear(comptime n: i32) !void {
// 長度為 n 的陣列佔用 O(n) 空間
- var nums = [_]i32{0}**n;
+ const nums = [_]i32{0} ** n;
// 長度為 n 的串列佔用 O(n) 空間
var nodes = std.ArrayList(i32).init(std.heap.page_allocator);
defer nodes.deinit();
@@ -85,23 +87,35 @@ fn quadratic(n: i32) !void {
// 平方階(遞迴實現)
fn quadraticRecur(comptime n: i32) i32 {
if (n <= 0) return 0;
- var nums = [_]i32{0}**n;
- std.debug.print("遞迴 n = {} 中的 nums 長度 = {}\n", .{n, nums.len});
+ const nums = [_]i32{0} ** n;
+ std.debug.print("遞迴 n = {} 中的 nums 長度 = {}\n", .{ n, nums.len });
return quadraticRecur(n - 1);
}
// 指數階(建立滿二元樹)
-fn buildTree(mem_allocator: std.mem.Allocator, n: i32) !?*inc.TreeNode(i32) {
+fn buildTree(allocator: std.mem.Allocator, n: i32) !?*TreeNode(i32) {
if (n == 0) return null;
- const root = try mem_allocator.create(inc.TreeNode(i32));
+ const root = try allocator.create(TreeNode(i32));
root.init(0);
- root.left = try buildTree(mem_allocator, n - 1);
- root.right = try buildTree(mem_allocator, n - 1);
+ root.left = try buildTree(allocator, n - 1);
+ root.right = try buildTree(allocator, n - 1);
return root;
}
+// 釋放樹的記憶體
+fn freeTree(allocator: std.mem.Allocator, root: ?*const TreeNode(i32)) void {
+ if (root == null) return;
+ freeTree(allocator, root.?.left);
+ freeTree(allocator, root.?.right);
+ allocator.destroy(root.?);
+}
+
// Driver Code
-pub fn main() !void {
+pub fn run() !void {
+ var gpa = std.heap.DebugAllocator(.{}){};
+ defer _ = gpa.deinit();
+ const allocator = gpa.allocator();
+
const n: i32 = 5;
// 常數階
constant(n);
@@ -112,13 +126,17 @@ pub fn main() !void {
try quadratic(n);
_ = quadraticRecur(n);
// 指數階
- var mem_arena = std.heap.ArenaAllocator.init(std.heap.page_allocator);
- defer mem_arena.deinit();
- var root = blk_root: {
- const mem_allocator = mem_arena.allocator();
- break :blk_root try buildTree(mem_allocator, n);
- };
- try inc.PrintUtil.printTree(root, null, false);
+ const root = try buildTree(allocator, n);
+ defer freeTree(allocator, root);
+ std.debug.print("{}\n", .{utils.fmt.tree(i32, root)});
- _ = try std.io.getStdIn().reader().readByte();
-}
\ No newline at end of file
+ std.debug.print("\n", .{});
+}
+
+pub fn main() !void {
+ try run();
+}
+
+test "space_complexity" {
+ try run();
+}
diff --git a/zh-hant/codes/zig/chapter_computational_complexity/time_complexity.zig b/zh-hant/codes/zig/chapter_computational_complexity/time_complexity.zig
index 3e592733d..a94ddc2d7 100644
--- a/zh-hant/codes/zig/chapter_computational_complexity/time_complexity.zig
+++ b/zh-hant/codes/zig/chapter_computational_complexity/time_complexity.zig
@@ -1,6 +1,6 @@
// File: time_complexity.zig
// Created Time: 2022-12-28
-// Author: codingonion (coderonion@gmail.com)
+// Author: codingonion (coderonion@gmail.com), CreatorMetaSky (creator_meta_sky@163.com)
const std = @import("std");
@@ -10,7 +10,7 @@ fn constant(n: i32) i32 {
var count: i32 = 0;
const size: i32 = 100_000;
var i: i32 = 0;
- while(i 0) : (i -= 1) {
@@ -61,10 +61,10 @@ fn bubbleSort(nums: []i32) i32 {
while (j < i) : (j += 1) {
if (nums[j] > nums[j + 1]) {
// 交換 nums[j] 與 nums[j + 1]
- var tmp = nums[j];
+ const tmp = nums[j];
nums[j] = nums[j + 1];
nums[j + 1] = tmp;
- count += 3; // 元素交換包含 3 個單元操作
+ count += 3; // 元素交換包含 3 個單元操作
}
}
}
@@ -97,11 +97,9 @@ fn expRecur(n: i32) i32 {
// 對數階(迴圈實現)
fn logarithmic(n: i32) i32 {
var count: i32 = 0;
- var n_var = n;
- while (n_var > 1)
- {
- n_var = n_var / 2;
- count +=1;
+ var n_var: i32 = n;
+ while (n_var > 1) : (n_var = @divTrunc(n_var, 2)) {
+ count += 1;
}
return count;
}
@@ -109,13 +107,13 @@ fn logarithmic(n: i32) i32 {
// 對數階(遞迴實現)
fn logRecur(n: i32) i32 {
if (n <= 1) return 0;
- return logRecur(n / 2) + 1;
+ return logRecur(@divTrunc(n, 2)) + 1;
}
// 線性對數階
fn linearLogRecur(n: i32) i32 {
if (n <= 1) return 1;
- var count: i32 = linearLogRecur(n / 2) + linearLogRecur(n / 2);
+ var count: i32 = linearLogRecur(@divTrunc(n, 2)) + linearLogRecur(@divTrunc(n, 2));
var i: i32 = 0;
while (i < n) : (i += 1) {
count += 1;
@@ -136,7 +134,7 @@ fn factorialRecur(n: i32) i32 {
}
// Driver Code
-pub fn main() !void {
+pub fn run() void {
// 可以修改 n 執行,體會一下各種複雜度的操作數量變化趨勢
const n: i32 = 8;
std.debug.print("輸入資料大小 n = {}\n", .{n});
@@ -146,14 +144,14 @@ pub fn main() !void {
count = linear(n);
std.debug.print("線性階的操作數量 = {}\n", .{count});
- var nums = [_]i32{0}**n;
+ var nums = [_]i32{0} ** n;
count = arrayTraversal(&nums);
std.debug.print("線性階(走訪陣列)的操作數量 = {}\n", .{count});
count = quadratic(n);
std.debug.print("平方階的操作數量 = {}\n", .{count});
for (&nums, 0..) |*num, i| {
- num.* = n - @as(i32, @intCast(i)); // [n,n-1,...,2,1]
+ num.* = n - @as(i32, @intCast(i)); // [n,n-1,...,2,1]
}
count = bubbleSort(&nums);
std.debug.print("平方階(泡沫排序)的操作數量 = {}\n", .{count});
@@ -174,6 +172,13 @@ pub fn main() !void {
count = factorialRecur(n);
std.debug.print("階乘階(遞迴實現)的操作數量 = {}\n", .{count});
- _ = try std.io.getStdIn().reader().readByte();
+ std.debug.print("\n", .{});
}
+pub fn main() !void {
+ run();
+}
+
+test "time_complexity" {
+ run();
+}
diff --git a/zh-hant/codes/zig/chapter_computational_complexity/worst_best_time_complexity.zig b/zh-hant/codes/zig/chapter_computational_complexity/worst_best_time_complexity.zig
index 8cd57d847..7d610852a 100644
--- a/zh-hant/codes/zig/chapter_computational_complexity/worst_best_time_complexity.zig
+++ b/zh-hant/codes/zig/chapter_computational_complexity/worst_best_time_complexity.zig
@@ -1,9 +1,9 @@
// File: worst_best_time_complexity.zig
// Created Time: 2022-12-28
-// Author: codingonion (coderonion@gmail.com)
+// Author: codingonion (coderonion@gmail.com), CreatorMetaSky (creator_meta_sky@163.com)
const std = @import("std");
-const inc = @import("include");
+const utils = @import("utils");
// 生成一個陣列,元素為 { 1, 2, ..., n },順序被打亂
pub fn randomNumbers(comptime n: usize) [n]i32 {
@@ -29,17 +29,25 @@ pub fn findOne(nums: []i32) i32 {
}
// Driver Code
-pub fn main() !void {
+pub fn run() void {
var i: i32 = 0;
while (i < 10) : (i += 1) {
const n: usize = 100;
var nums = randomNumbers(n);
- var index = findOne(&nums);
- std.debug.print("\n陣列 [ 1, 2, ..., n ] 被打亂後 = ", .{});
- inc.PrintUtil.printArray(i32, &nums);
+ const index = findOne(&nums);
+ std.debug.print("陣列 [ 1, 2, ..., n ] 被打亂後 = ", .{});
+ std.debug.print("{}\n", .{utils.fmt.slice(nums)});
+
std.debug.print("數字 1 的索引為 {}\n", .{index});
}
- _ = try std.io.getStdIn().reader().readByte();
+ std.debug.print("\n", .{});
}
+pub fn main() !void {
+ run();
+}
+
+test "worst_best_time_complexity" {
+ run();
+}
diff --git a/zh-hant/codes/zig/include/PrintUtil.zig b/zh-hant/codes/zig/include/PrintUtil.zig
index c7444e99f..4bc5988f9 100644
--- a/zh-hant/codes/zig/include/PrintUtil.zig
+++ b/zh-hant/codes/zig/include/PrintUtil.zig
@@ -8,45 +8,6 @@ pub const ListNode = ListUtil.ListNode;
pub const TreeUtil = @import("TreeNode.zig");
pub const TreeNode = TreeUtil.TreeNode;
-// 列印陣列
-pub fn printArray(comptime T: type, nums: []T) void {
- std.debug.print("[", .{});
- if (nums.len > 0) {
- for (nums, 0..) |num, j| {
- std.debug.print("{}{s}", .{num, if (j == nums.len-1) "]" else ", " });
- }
- } else {
- std.debug.print("]", .{});
- }
-}
-
-// 列印串列
-pub fn printList(comptime T: type, list: std.ArrayList(T)) void {
- std.debug.print("[", .{});
- if (list.items.len > 0) {
- for (list.items, 0..) |value, i| {
- std.debug.print("{}{s}", .{value, if (i == list.items.len-1) "]" else ", " });
- }
- } else {
- std.debug.print("]", .{});
- }
-}
-
-// 列印鏈結串列
-pub fn printLinkedList(comptime T: type, node: ?*ListNode(T)) !void {
- if (node == null) return;
- var list = std.ArrayList(T).init(std.heap.page_allocator);
- defer list.deinit();
- var head = node;
- while (head != null) {
- try list.append(head.?.val);
- head = head.?.next;
- }
- for (list.items, 0..) |value, i| {
- std.debug.print("{}{s}", .{value, if (i == list.items.len-1) "\n" else "->" });
- }
-}
-
// 列印佇列
pub fn printQueue(comptime T: type, queue: std.TailQueue(T)) void {
var node = queue.first;
@@ -54,7 +15,7 @@ pub fn printQueue(comptime T: type, queue: std.TailQueue(T)) void {
var i: i32 = 0;
while (node != null) : (i += 1) {
var data = node.?.data;
- std.debug.print("{}{s}", .{data, if (i == queue.len - 1) "]" else ", " });
+ std.debug.print("{}{s}", .{ data, if (i == queue.len - 1) "]" else ", " });
node = node.?.next;
}
}
@@ -65,7 +26,7 @@ pub fn printHashMap(comptime TKey: type, comptime TValue: type, map: std.AutoHas
while (it.next()) |kv| {
var key = kv.key_ptr.*;
var value = kv.value_ptr.*;
- std.debug.print("{} -> {s}\n", .{key, value});
+ std.debug.print("{} -> {s}\n", .{ key, value });
}
}
@@ -79,54 +40,3 @@ pub fn printHeap(comptime T: type, mem_allocator: std.mem.Allocator, queue: anyt
var root = try TreeUtil.arrToTree(T, mem_allocator, arr[0..len]);
try printTree(root, null, false);
}
-
-// 列印二元樹
-// This tree printer is borrowed from TECHIE DELIGHT
-// https://www.techiedelight.com/c-program-print-binary-tree/
-const Trunk = struct {
- prev: ?*Trunk = null,
- str: []const u8 = undefined,
-
- pub fn init(self: *Trunk, prev: ?*Trunk, str: []const u8) void {
- self.prev = prev;
- self.str = str;
- }
-};
-
-pub fn showTrunks(p: ?*Trunk) void {
- if (p == null) return;
- showTrunks(p.?.prev);
- std.debug.print("{s}", .{p.?.str});
-}
-
-// 列印二元樹
-pub fn printTree(root: ?*TreeNode(i32), prev: ?*Trunk, isRight: bool) !void {
- if (root == null) {
- return;
- }
-
- var prev_str = " ";
- var trunk = Trunk{.prev = prev, .str = prev_str};
-
- try printTree(root.?.right, &trunk, true);
-
- if (prev == null) {
- trunk.str = "———";
- } else if (isRight) {
- trunk.str = "/———";
- prev_str = " |";
- } else {
- trunk.str = "\\———";
- prev.?.str = prev_str;
- }
-
- showTrunks(&trunk);
- std.debug.print(" {}\n", .{root.?.val});
-
- if (prev) |_| {
- prev.?.str = prev_str;
- }
- trunk.str = " |";
-
- try printTree(root.?.left, &trunk, false);
-}
\ No newline at end of file
diff --git a/zh-hant/codes/zig/include/include.zig b/zh-hant/codes/zig/include/include.zig
index cb98ffc0d..4c4ec8369 100644
--- a/zh-hant/codes/zig/include/include.zig
+++ b/zh-hant/codes/zig/include/include.zig
@@ -3,7 +3,5 @@
// Author: codingonion (coderonion@gmail.com)
pub const PrintUtil = @import("PrintUtil.zig");
-pub const ListUtil = @import("ListNode.zig");
-pub const ListNode = ListUtil.ListNode;
pub const TreeUtil = @import("TreeNode.zig");
-pub const TreeNode = TreeUtil.TreeNode;
\ No newline at end of file
+pub const TreeNode = TreeUtil.TreeNode;
diff --git a/zh-hant/codes/zig/main.zig b/zh-hant/codes/zig/main.zig
new file mode 100644
index 000000000..970449d97
--- /dev/null
+++ b/zh-hant/codes/zig/main.zig
@@ -0,0 +1,25 @@
+const std = @import("std");
+
+const iteration = @import("chapter_computational_complexity/iteration.zig");
+const recursion = @import("chapter_computational_complexity/recursion.zig");
+const time_complexity = @import("chapter_computational_complexity/time_complexity.zig");
+const space_complexity = @import("chapter_computational_complexity/space_complexity.zig");
+const worst_best_time_complexity = @import("chapter_computational_complexity/worst_best_time_complexity.zig");
+
+const array = @import("chapter_array_and_linkedlist/array.zig");
+const linked_list = @import("chapter_array_and_linkedlist/linked_list.zig");
+const list = @import("chapter_array_and_linkedlist/list.zig");
+const my_list = @import("chapter_array_and_linkedlist/my_list.zig");
+
+pub fn main() !void {
+ try iteration.run();
+ recursion.run();
+ time_complexity.run();
+ try space_complexity.run();
+ worst_best_time_complexity.run();
+
+ try array.run();
+ linked_list.run();
+ try list.run();
+ try my_list.run();
+}
diff --git a/zh-hant/codes/zig/utils/ListNode.zig b/zh-hant/codes/zig/utils/ListNode.zig
new file mode 100644
index 000000000..113fd4130
--- /dev/null
+++ b/zh-hant/codes/zig/utils/ListNode.zig
@@ -0,0 +1,49 @@
+// File: ListNode.zig
+// Created Time: 2023-01-07
+// Author: codingonion (coderonion@gmail.com), CreatorMetaSky (creator_meta_sky@163.com)
+
+const std = @import("std");
+
+// 鏈結串列節點
+pub fn ListNode(comptime T: type) type {
+ return struct {
+ const Self = @This();
+
+ val: T = 0,
+ next: ?*Self = null,
+
+ // Initialize a list node with specific value
+ pub fn init(self: *Self, x: i32) void {
+ self.val = x;
+ self.next = null;
+ }
+ };
+}
+
+// 將串列反序列化為鏈結串列
+pub fn listToLinkedList(comptime T: type, allocator: std.mem.Allocator, list: std.ArrayList(T)) !?*ListNode(T) {
+ var dum = try allocator.create(ListNode(T));
+ dum.init(0);
+ var head = dum;
+ for (list.items) |val| {
+ var tmp = try allocator.create(ListNode(T));
+ tmp.init(val);
+ head.next = tmp;
+ head = head.next.?;
+ }
+ return dum.next;
+}
+
+// 將陣列反序列化為鏈結串列
+pub fn arrToLinkedList(comptime T: type, mem_allocator: std.mem.Allocator, arr: []T) !?*ListNode(T) {
+ var dum = try mem_allocator.create(ListNode(T));
+ dum.init(0);
+ var head = dum;
+ for (arr) |val| {
+ var tmp = try mem_allocator.create(ListNode(T));
+ tmp.init(val);
+ head.next = tmp;
+ head = head.next.?;
+ }
+ return dum.next;
+}
diff --git a/zh-hant/codes/zig/utils/TreeNode.zig b/zh-hant/codes/zig/utils/TreeNode.zig
new file mode 100644
index 000000000..7764b00f0
--- /dev/null
+++ b/zh-hant/codes/zig/utils/TreeNode.zig
@@ -0,0 +1,63 @@
+// File: TreeNode.zig
+// Created Time: 2023-01-07
+// Author: codingonion (coderonion@gmail.com), CreatorMetaSky (creator_meta_sky@163.com)
+
+const std = @import("std");
+
+// 二元樹節點
+pub fn TreeNode(comptime T: type) type {
+ return struct {
+ const Self = @This();
+
+ val: T = undefined, // 節點值
+ height: i32 = undefined, // 節點高度
+ left: ?*Self = null, // 左子節點指標
+ right: ?*Self = null, // 右子節點指標
+
+ // Initialize a tree node with specific value
+ pub fn init(self: *Self, x: i32) void {
+ self.val = x;
+ self.height = 0;
+ self.left = null;
+ self.right = null;
+ }
+ };
+}
+
+// 將陣列反序列化為二元樹
+pub fn arrToTree(comptime T: type, allocator: std.mem.Allocator, arr: []T) !?*TreeNode(T) {
+ if (arr.len == 0) return null;
+ var root = try allocator.create(TreeNode(T));
+ root.init(arr[0]);
+ const L = std.TailQueue(*TreeNode(T));
+ var que = L{};
+ var root_node = try allocator.create(L.Node);
+ root_node.data = root;
+ que.append(root_node);
+ var index: usize = 0;
+ while (que.len > 0) {
+ const que_node = que.popFirst().?;
+ var node = que_node.data;
+ index += 1;
+ if (index >= arr.len) break;
+ if (index < arr.len) {
+ var tmp = try allocator.create(TreeNode(T));
+ tmp.init(arr[index]);
+ node.left = tmp;
+ var tmp_node = try allocator.create(L.Node);
+ tmp_node.data = node.left.?;
+ que.append(tmp_node);
+ }
+ index += 1;
+ if (index >= arr.len) break;
+ if (index < arr.len) {
+ var tmp = try allocator.create(TreeNode(T));
+ tmp.init(arr[index]);
+ node.right = tmp;
+ var tmp_node = try allocator.create(L.Node);
+ tmp_node.data = node.right.?;
+ que.append(tmp_node);
+ }
+ }
+ return root;
+}
diff --git a/zh-hant/codes/zig/utils/format.zig b/zh-hant/codes/zig/utils/format.zig
new file mode 100644
index 000000000..0d9b96801
--- /dev/null
+++ b/zh-hant/codes/zig/utils/format.zig
@@ -0,0 +1,140 @@
+// File: format.zig
+// Created Time: 2025-07-19
+// Author: CreatorMetaSky (creator_meta_sky@163.com)
+
+const std = @import("std");
+const ListNode = @import("ListNode.zig").ListNode;
+const TreeNode = @import("TreeNode.zig").TreeNode;
+
+pub fn slice(items: anytype) SliceFormatter(@TypeOf(items)) {
+ return .{ .items = items };
+}
+
+pub fn SliceFormatter(comptime SliceType: type) type {
+ return struct {
+ const Self = @This();
+
+ items: SliceType,
+
+ pub fn format(
+ self: Self,
+ comptime _: []const u8,
+ _: std.fmt.FormatOptions,
+ writer: anytype,
+ ) !void {
+ try writer.writeAll("[");
+
+ if (self.items.len > 0) {
+ for (self.items, 0..) |item, i| {
+ try std.fmt.format(writer, "{}", .{item});
+ if (i != self.items.len - 1) {
+ try writer.writeAll(", ");
+ }
+ }
+ }
+
+ try writer.writeAll("]");
+ }
+ };
+}
+
+pub fn linkedList(comptime T: type, head: *const ListNode(T)) LinkedListFormatter(T) {
+ return .{ .head = head };
+}
+
+pub fn LinkedListFormatter(comptime T: type) type {
+ return struct {
+ const Self = @This();
+
+ head: *const ListNode(T),
+
+ pub fn format(
+ self: Self,
+ comptime _: []const u8,
+ _: std.fmt.FormatOptions,
+ writer: anytype,
+ ) !void {
+ try printLinkedList(self.head, writer);
+ }
+
+ pub fn printLinkedList(head: *const ListNode(T), writer: anytype) !void {
+ try std.fmt.format(writer, "{}", .{head.val});
+ if (head.next) |next_node| {
+ try writer.writeAll("->");
+ try printLinkedList(next_node, writer);
+ }
+ }
+ };
+}
+
+pub fn tree(comptime T: type, root: ?*const TreeNode(T)) TreeFormatter(T) {
+ return .{ .root = root };
+}
+
+pub fn TreeFormatter(comptime T: type) type {
+ return struct {
+ const Self = @This();
+
+ root: ?*const TreeNode(T),
+
+ pub fn format(
+ self: Self,
+ comptime _: []const u8,
+ _: std.fmt.FormatOptions,
+ writer: anytype,
+ ) !void {
+ try printTree(self.root, null, false, writer);
+ }
+
+ // 列印二元樹
+ fn printTree(root: ?*const TreeNode(T), prev: ?*Trunk, isRight: bool, writer: anytype) !void {
+ if (root == null) {
+ return;
+ }
+
+ var prev_str = " ";
+ var trunk = Trunk{ .prev = prev, .str = prev_str };
+
+ try printTree(root.?.right, &trunk, true, writer);
+
+ if (prev == null) {
+ trunk.str = "———";
+ } else if (isRight) {
+ trunk.str = "/———";
+ prev_str = " |";
+ } else {
+ trunk.str = "\\———";
+ prev.?.str = prev_str;
+ }
+
+ try showTrunks(&trunk, writer);
+ try std.fmt.format(writer, "{d}\n", .{root.?.val});
+
+ if (prev) |_| {
+ prev.?.str = prev_str;
+ }
+ trunk.str = " |";
+
+ try printTree(root.?.left, &trunk, false, writer);
+ }
+
+ // 列印二元樹
+ // This tree printer is borrowed from TECHIE DELIGHT
+ // https://www.techiedelight.com/c-program-print-binary-tree/
+ const Trunk = struct {
+ prev: ?*Trunk = null,
+ str: []const u8 = undefined,
+
+ pub fn init(self: *Trunk, prev: ?*Trunk, str: []const u8) void {
+ self.prev = prev;
+ self.str = str;
+ }
+ };
+
+ pub fn showTrunks(p: ?*Trunk, writer: anytype) !void {
+ if (p == null) return;
+ try showTrunks(p.?.prev, writer);
+ try std.fmt.format(writer, "{s}", .{p.?.str});
+ }
+ };
+}
diff --git a/zh-hant/codes/zig/utils/utils.zig b/zh-hant/codes/zig/utils/utils.zig
new file mode 100644
index 000000000..a3d53797c
--- /dev/null
+++ b/zh-hant/codes/zig/utils/utils.zig
@@ -0,0 +1,8 @@
+// File: format.zig
+// Created Time: 2025-07-15
+// Author: CreatorMetaSky (creator_meta_sky@163.com)
+
+const std = @import("std");
+pub const fmt = @import("format.zig");
+pub const ListNode = @import("ListNode.zig").ListNode;
+pub const TreeNode = @import("TreeNode.zig").TreeNode;
diff --git a/zh-hant/docs/chapter_array_and_linkedlist/array.md b/zh-hant/docs/chapter_array_and_linkedlist/array.md
index 823d0103b..8d8176a2d 100755
--- a/zh-hant/docs/chapter_array_and_linkedlist/array.md
+++ b/zh-hant/docs/chapter_array_and_linkedlist/array.md
@@ -15,7 +15,7 @@
```python title="array.py"
# 初始化陣列
arr: list[int] = [0] * 5 # [ 0, 0, 0, 0, 0 ]
- nums: list[int] = [1, 3, 2, 5, 4]
+ nums: list[int] = [1, 3, 2, 5, 4]
```
=== "C++"
@@ -130,8 +130,8 @@
```zig title="array.zig"
// 初始化陣列
- var arr = [_]i32{0} ** 5; // { 0, 0, 0, 0, 0 }
- var nums = [_]i32{ 1, 3, 2, 5, 4 };
+ const arr = [_]i32{0} ** 5; // { 0, 0, 0, 0, 0 }
+ const nums = [_]i32{ 1, 3, 2, 5, 4 };
```
??? pythontutor "視覺化執行"
diff --git a/zh-hant/docs/chapter_computational_complexity/performance_evaluation.md b/zh-hant/docs/chapter_computational_complexity/performance_evaluation.md
index b97c7a325..c41d175c2 100644
--- a/zh-hant/docs/chapter_computational_complexity/performance_evaluation.md
+++ b/zh-hant/docs/chapter_computational_complexity/performance_evaluation.md
@@ -26,10 +26,10 @@
由於實際測試具有較大的侷限性,我們可以考慮僅透過一些計算來評估演算法的效率。這種估算方法被稱為漸近複雜度分析(asymptotic complexity analysis),簡稱複雜度分析。
-複雜度分析能夠體現演算法執行所需的時間和空間資源與輸入資料大小之間的關係。**它描述了隨著輸入資料大小的增加,演算法執行所需時間和空間的增長趨勢**。這個定義有些拗口,我們可以將其分為三個重點來理解。
+複雜度分析能夠體現演算法執行所需的時間和空間資源與輸入資料規模之間的關係。**它描述了隨著輸入資料規模的增加,演算法執行所需時間和空間的增長趨勢**。這個定義有些拗口,我們可以將其分為三個重點來理解。
- “時間和空間資源”分別對應時間複雜度(time complexity)和空間複雜度(space complexity)。
-- “隨著輸入資料大小的增加”意味著複雜度反映了演算法執行效率與輸入資料體量之間的關係。
+- “隨著輸入資料規模的增加”意味著複雜度反映了演算法執行效率與輸入資料規模之間的關係。
- “時間和空間的增長趨勢”表示複雜度分析關注的不是執行時間或佔用空間的具體值,而是時間或空間增長的“快慢”。
**複雜度分析克服了實際測試方法的弊端**,體現在以下幾個方面。
diff --git a/zh-hant/docs/chapter_computational_complexity/summary.md b/zh-hant/docs/chapter_computational_complexity/summary.md
index 6ce0745d3..26cd8f2d0 100644
--- a/zh-hant/docs/chapter_computational_complexity/summary.md
+++ b/zh-hant/docs/chapter_computational_complexity/summary.md
@@ -47,3 +47,9 @@
假設取 $n = 8$ ,你可能會發現每條曲線的值與函式對應不上。這是因為每條曲線都包含一個常數項,用於將取值範圍壓縮到一個視覺舒適的範圍內。
在實際中,因為我們通常不知道每個方法的“常數項”複雜度是多少,所以一般無法僅憑複雜度來選擇 $n = 8$ 之下的最優解法。但對於 $n = 8^5$ 就很好選了,這時增長趨勢已經佔主導了。
+
+**Q** 是否存在根據實際使用場景,選擇犧牲時間(或空間)來設計演算法的情況?
+
+在實際應用中,大部分情況會選擇犧牲空間換時間。例如資料庫索引,我們通常選擇建立 B+ 樹或雜湊索引,佔用大量記憶體空間,以換取 $O(\log n)$ 甚至 $O(1)$ 的高效查詢。
+
+在空間資源寶貴的場景,也會選擇犧牲時間換空間。例如在嵌入式開發中,裝置記憶體很寶貴,工程師可能會放棄使用雜湊表,選擇使用陣列順序查詢,以節省記憶體佔用,代價是查詢變慢。
diff --git a/zh-hant/docs/chapter_dynamic_programming/dp_solution_pipeline.md b/zh-hant/docs/chapter_dynamic_programming/dp_solution_pipeline.md
index 777a8b751..13026aabd 100644
--- a/zh-hant/docs/chapter_dynamic_programming/dp_solution_pipeline.md
+++ b/zh-hant/docs/chapter_dynamic_programming/dp_solution_pipeline.md
@@ -110,7 +110,7 @@ $$

-每個狀態都有向下和向右兩種選擇,從左上角走到右下角總共需要 $m + n - 2$ 步,所以最差時間複雜度為 $O(2^{m + n})$ ,其中 $n$ 和 $m$ 分別為網格的行數和列數。請注意,這種計算方式未考慮臨近網格邊界的情況,當到達網路邊界時只剩下一種選擇,因此實際的路徑數量會少一些。
+每個狀態都有向下和向右兩種選擇,從左上角走到右下角總共需要 $m + n - 2$ 步,所以最差時間複雜度為 $O(2^{m + n})$ ,其中 $n$ 和 $m$ 分別為網格的行數和列數。請注意,這種計算方式未考慮臨近網格邊界的情況,當到達網格邊界時只剩下一種選擇,因此實際的路徑數量會少一些。
### 方法二:記憶化搜尋
diff --git a/zh-hant/docs/chapter_hashing/hash_map.md b/zh-hant/docs/chapter_hashing/hash_map.md
index b785fe178..cdfecb7bb 100755
--- a/zh-hant/docs/chapter_hashing/hash_map.md
+++ b/zh-hant/docs/chapter_hashing/hash_map.md
@@ -559,7 +559,7 @@
輸入一個 `key` ,雜湊函式的計算過程分為以下兩步。
1. 透過某種雜湊演算法 `hash()` 計算得到雜湊值。
-2. 將雜湊值對桶數量(陣列長度)`capacity` 取模,從而獲取該 `key` 對應的陣列索引 `index` 。
+2. 將雜湊值對桶數量(陣列長度)`capacity` 取模,從而獲取該 `key` 對應的桶(陣列索引)`index` 。
```shell
index = hash(key) % capacity
diff --git a/zh-hant/docs/chapter_hashing/summary.md b/zh-hant/docs/chapter_hashing/summary.md
index c80102b9d..eb373ac3e 100644
--- a/zh-hant/docs/chapter_hashing/summary.md
+++ b/zh-hant/docs/chapter_hashing/summary.md
@@ -45,3 +45,7 @@
**Q**:為什麼雜湊表擴容能夠緩解雜湊衝突?
雜湊函式的最後一步往往是對陣列長度 $n$ 取模(取餘),讓輸出值落在陣列索引範圍內;在擴容後,陣列長度 $n$ 發生變化,而 `key` 對應的索引也可能發生變化。原先落在同一個桶的多個 `key` ,在擴容後可能會被分配到多個桶中,從而實現雜湊衝突的緩解。
+
+**Q**:如果為了高效的存取,那麼直接使用陣列不就好了嗎?
+
+當資料的 `key` 是連續的小範圍整數時,直接用陣列即可,簡單高效。但當 `key` 是其他型別(例如字串)時,就需要藉助雜湊函式將 `key` 對映為陣列索引,再透過桶陣列儲存元素,這樣的結構就是雜湊表。
diff --git a/zh-hant/docs/chapter_searching/searching_algorithm_revisited.md b/zh-hant/docs/chapter_searching/searching_algorithm_revisited.md
index 0ce25d722..04bd57da0 100644
--- a/zh-hant/docs/chapter_searching/searching_algorithm_revisited.md
+++ b/zh-hant/docs/chapter_searching/searching_algorithm_revisited.md
@@ -55,7 +55,7 @@
| 資料預處理 | / | 排序 $O(n \log n)$ | 建樹 $O(n \log n)$ | 建雜湊表 $O(n)$ |
| 資料是否有序 | 無序 | 有序 | 有序 | 無序 |
-搜尋演算法的選擇還取決於資料體量、搜尋效能要求、資料查詢與更新頻率等。
+搜尋演算法的選擇還取決規模、搜尋效能要求、資料查詢與更新頻率等。
**線性搜尋**
diff --git a/zh-hant/docs/chapter_searching/summary.md b/zh-hant/docs/chapter_searching/summary.md
index 964158c9a..0c50a4934 100644
--- a/zh-hant/docs/chapter_searching/summary.md
+++ b/zh-hant/docs/chapter_searching/summary.md
@@ -3,6 +3,6 @@
- 二分搜尋依賴資料的有序性,透過迴圈逐步縮減一半搜尋區間來進行查詢。它要求輸入資料有序,且僅適用於陣列或基於陣列實現的資料結構。
- 暴力搜尋透過走訪資料結構來定位資料。線性搜尋適用於陣列和鏈結串列,廣度優先搜尋和深度優先搜尋適用於圖和樹。此類演算法通用性好,無須對資料進行預處理,但時間複雜度 $O(n)$ 較高。
- 雜湊查詢、樹查詢和二分搜尋屬於高效搜尋方法,可在特定資料結構中快速定位目標元素。此類演算法效率高,時間複雜度可達 $O(\log n)$ 甚至 $O(1)$ ,但通常需要藉助額外資料結構。
-- 實際中,我們需要對資料體量、搜尋效能要求、資料查詢和更新頻率等因素進行具體分析,從而選擇合適的搜尋方法。
+- 實際中,我們需要對資料規模、搜尋效能要求、資料查詢和更新頻率等因素進行具體分析,從而選擇合適的搜尋方法。
- 線性搜尋適用於小型或頻繁更新的資料;二分搜尋適用於大型、排序的資料;雜湊查詢適用於對查詢效率要求較高且無須範圍查詢的資料;樹查詢適用於需要維護順序和支持範圍查詢的大型動態資料。
- 用雜湊查詢替換線性查詢是一種常用的最佳化執行時間的策略,可將時間複雜度從 $O(n)$ 降至 $O(1)$ 。
diff --git a/zh-hant/docs/chapter_stack_and_queue/stack.md b/zh-hant/docs/chapter_stack_and_queue/stack.md
index e87ff00fd..0a979c9cf 100755
--- a/zh-hant/docs/chapter_stack_and_queue/stack.md
+++ b/zh-hant/docs/chapter_stack_and_queue/stack.md
@@ -2,7 +2,7 @@
堆疊(stack)是一種遵循先入後出邏輯的線性資料結構。
-我們可以將堆疊類比為桌面上的一疊盤子,如果想取出底部的盤子,則需要先將上面的盤子依次移走。我們將盤子替換為各種型別的元素(如整數、字元、物件等),就得到了堆疊這種資料結構。
+我們可以將堆疊類比為桌面上的一疊盤子,規定每次只能移動一個盤子,那麼想取出底部的盤子,則需要先將上面的盤子依次移走。我們將盤子替換為各種型別的元素(如整數、字元、物件等),就得到了堆疊這種資料結構。
如下圖所示,我們把堆積疊元素的頂部稱為“堆疊頂”,底部稱為“堆疊底”。將把元素新增到堆疊頂的操作叫作“入堆疊”,刪除堆疊頂元素的操作叫作“出堆疊”。
diff --git a/zh-hant/docs/index.html b/zh-hant/docs/index.html
index b5cdd8ebd..f22e4f9e8 100644
--- a/zh-hant/docs/index.html
+++ b/zh-hant/docs/index.html
@@ -237,8 +237,24 @@
+
+
+
-