mirror of
https://github.com/krahets/hello-algo.git
synced 2026-11-26 05:33:40 +08:00
Retire unbuilt Zig code, fail on unknown Docker languages, fit Russian Tutor links (#2029)
- Zig (all six editions): delete the 38 chapter files that build.zig never built and the stale include/ module (plus two zh-hant orphans); build.zig keeps the two built chapters, drops the temporary allowlist and fails instead of skipping directory or module errors. The Zig workflow also builds the English edition. - codes/Dockerfile (all six editions): a language without an installation workflow now prints an error to stderr and exits 1 instead of printing a warning. - ru PythonTutor: regenerate all 126 links; 18 snippets over the 5,600-byte payload budget drop their comments, and the quick sort tail-recursion caption is corrected. Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
6
.github/workflows/zig.yml
vendored
6
.github/workflows/zig.yml
vendored
@@ -6,9 +6,11 @@ on:
|
||||
paths:
|
||||
- ".github/workflows/zig.yml"
|
||||
- "codes/zig/**/*.zig"
|
||||
- "en/codes/zig/**/*.zig"
|
||||
- "ja/codes/zig/**/*.zig"
|
||||
- "ko/codes/zig/**/*.zig"
|
||||
- "codes/zig/build.zig"
|
||||
- "en/codes/zig/build.zig"
|
||||
- "ja/codes/zig/build.zig"
|
||||
- "ko/codes/zig/build.zig"
|
||||
pull_request:
|
||||
@@ -16,9 +18,11 @@ on:
|
||||
paths:
|
||||
- ".github/workflows/zig.yml"
|
||||
- "codes/zig/**/*.zig"
|
||||
- "en/codes/zig/**/*.zig"
|
||||
- "ja/codes/zig/**/*.zig"
|
||||
- "ko/codes/zig/**/*.zig"
|
||||
- "codes/zig/build.zig"
|
||||
- "en/codes/zig/build.zig"
|
||||
- "ja/codes/zig/build.zig"
|
||||
- "ko/codes/zig/build.zig"
|
||||
workflow_dispatch:
|
||||
@@ -33,7 +37,7 @@ jobs:
|
||||
matrix:
|
||||
# Keep the macOS SDK compatible with Zig 0.14.1.
|
||||
os: [ubuntu-latest, macos-14, windows-latest]
|
||||
code-dir: ["codes/zig", "ja/codes/zig", "ko/codes/zig"]
|
||||
code-dir: ["codes/zig", "en/codes/zig", "ja/codes/zig", "ko/codes/zig"]
|
||||
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
|
||||
@@ -25,7 +25,7 @@ RUN for LANG in $LANGS; do \
|
||||
apt-get install -y dotnet-sdk-8.0 ;; \
|
||||
# More languages...
|
||||
*) \
|
||||
echo "Warning: No installation workflow for $LANG" ;; \
|
||||
echo "Error: No installation workflow for $LANG" >&2; exit 1 ;; \
|
||||
esac \
|
||||
done
|
||||
|
||||
|
||||
@@ -16,13 +16,6 @@ pub fn build(b: *std.Build) void {
|
||||
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",
|
||||
};
|
||||
|
||||
const test_step = b.step("test", "Run unit tests");
|
||||
@@ -41,14 +34,13 @@ fn buildChapterExeModules(
|
||||
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;
|
||||
var chapter_dir = std.fs.cwd().openDir(chapter_dir_name, .{ .iterate = true }) catch |err| @panic(@errorName(err));
|
||||
defer chapter_dir.close();
|
||||
|
||||
var it = chapter_dir.iterate();
|
||||
while (it.next() catch continue) |chapter_dir_entry| {
|
||||
while (it.next() catch |err| @panic(@errorName(err))) |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;
|
||||
const exe_mod = buildExeModuleFromChapterDirEntry(b, target, optimize, chapter_dir_name, chapter_dir_entry) catch |err| @panic(@errorName(err));
|
||||
addTestStepToExeModule(b, test_step, exe_mod, test_filters);
|
||||
}
|
||||
}
|
||||
@@ -64,30 +56,6 @@ fn buildExeModuleFromChapterDirEntry(
|
||||
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,
|
||||
|
||||
@@ -1,44 +0,0 @@
|
||||
// File: climbing_stairs_backtrack.zig
|
||||
// Created Time: 2023-07-15
|
||||
// Author: codingonion (coderonion@gmail.com)
|
||||
|
||||
const std = @import("std");
|
||||
|
||||
// 回溯
|
||||
fn backtrack(choices: []i32, state: i32, n: i32, res: std.ArrayList(i32)) void {
|
||||
// 当爬到第 n 阶时,方案数量加 1
|
||||
if (state == n) {
|
||||
res.items[0] = res.items[0] + 1;
|
||||
}
|
||||
// 遍历所有选择
|
||||
for (choices) |choice| {
|
||||
// 剪枝:不允许越过第 n 阶
|
||||
if (state + choice > n) {
|
||||
continue;
|
||||
}
|
||||
// 尝试:做出选择,更新状态
|
||||
backtrack(choices, state + choice, n, res);
|
||||
// 回退
|
||||
}
|
||||
}
|
||||
|
||||
// 爬楼梯:回溯
|
||||
fn climbingStairsBacktrack(n: usize) !i32 {
|
||||
var choices = [_]i32{ 1, 2 }; // 可选择向上爬 1 阶或 2 阶
|
||||
var state: i32 = 0; // 从第 0 阶开始爬
|
||||
var res = std.ArrayList(i32).init(std.heap.page_allocator);
|
||||
defer res.deinit();
|
||||
try res.append(0); // 使用 res[0] 记录方案数量
|
||||
backtrack(&choices, state, @intCast(n), res);
|
||||
return res.items[0];
|
||||
}
|
||||
|
||||
// Driver Code
|
||||
pub fn main() !void {
|
||||
var n: usize = 9;
|
||||
|
||||
var res = try climbingStairsBacktrack(n);
|
||||
std.debug.print("爬 {} 阶楼梯共有 {} 种方案\n", .{ n, res });
|
||||
|
||||
_ = try std.io.getStdIn().reader().readByte();
|
||||
}
|
||||
@@ -1,35 +0,0 @@
|
||||
// File: climbing_stairs_constraint_dp.zig
|
||||
// Created Time: 2023-07-15
|
||||
// Author: codingonion (coderonion@gmail.com)
|
||||
|
||||
const std = @import("std");
|
||||
|
||||
// 带约束爬楼梯:动态规划
|
||||
fn climbingStairsConstraintDP(comptime n: usize) i32 {
|
||||
if (n == 1 or n == 2) {
|
||||
return 1;
|
||||
}
|
||||
// 初始化 dp 表,用于存储子问题的解
|
||||
var dp = [_][3]i32{ [_]i32{ -1, -1, -1 } } ** (n + 1);
|
||||
// 初始状态:预设最小子问题的解
|
||||
dp[1][1] = 1;
|
||||
dp[1][2] = 0;
|
||||
dp[2][1] = 0;
|
||||
dp[2][2] = 1;
|
||||
// 状态转移:从较小子问题逐步求解较大子问题
|
||||
for (3..n + 1) |i| {
|
||||
dp[i][1] = dp[i - 1][2];
|
||||
dp[i][2] = dp[i - 2][1] + dp[i - 2][2];
|
||||
}
|
||||
return dp[n][1] + dp[n][2];
|
||||
}
|
||||
|
||||
// Driver Code
|
||||
pub fn main() !void {
|
||||
comptime var n: usize = 9;
|
||||
|
||||
var res = climbingStairsConstraintDP(n);
|
||||
std.debug.print("爬 {} 阶楼梯共有 {} 种方案\n", .{ n, res });
|
||||
|
||||
_ = try std.io.getStdIn().reader().readByte();
|
||||
}
|
||||
@@ -1,31 +0,0 @@
|
||||
// File: climbing_stairs_dfs.zig
|
||||
// Created Time: 2023-07-15
|
||||
// Author: codingonion (coderonion@gmail.com)
|
||||
|
||||
const std = @import("std");
|
||||
|
||||
// 搜索
|
||||
fn dfs(i: usize) i32 {
|
||||
// 已知 dp[1] 和 dp[2] ,返回之
|
||||
if (i == 1 or i == 2) {
|
||||
return @intCast(i);
|
||||
}
|
||||
// dp[i] = dp[i-1] + dp[i-2]
|
||||
var count = dfs(i - 1) + dfs(i - 2);
|
||||
return count;
|
||||
}
|
||||
|
||||
// 爬楼梯:搜索
|
||||
fn climbingStairsDFS(comptime n: usize) i32 {
|
||||
return dfs(n);
|
||||
}
|
||||
|
||||
// Driver Code
|
||||
pub fn main() !void {
|
||||
comptime var n: usize = 9;
|
||||
|
||||
var res = climbingStairsDFS(n);
|
||||
std.debug.print("爬 {} 阶楼梯共有 {} 种方案\n", .{ n, res });
|
||||
|
||||
_ = try std.io.getStdIn().reader().readByte();
|
||||
}
|
||||
@@ -1,39 +0,0 @@
|
||||
// File: climbing_stairs_dfs_mem.zig
|
||||
// Created Time: 2023-07-15
|
||||
// Author: codingonion (coderonion@gmail.com)
|
||||
|
||||
const std = @import("std");
|
||||
|
||||
// 记忆化搜索
|
||||
fn dfs(i: usize, mem: []i32) i32 {
|
||||
// 已知 dp[1] 和 dp[2] ,返回之
|
||||
if (i == 1 or i == 2) {
|
||||
return @intCast(i);
|
||||
}
|
||||
// 若存在记录 dp[i] ,则直接返回之
|
||||
if (mem[i] != -1) {
|
||||
return mem[i];
|
||||
}
|
||||
// dp[i] = dp[i-1] + dp[i-2]
|
||||
var count = dfs(i - 1, mem) + dfs(i - 2, mem);
|
||||
// 记录 dp[i]
|
||||
mem[i] = count;
|
||||
return count;
|
||||
}
|
||||
|
||||
// 爬楼梯:记忆化搜索
|
||||
fn climbingStairsDFSMem(comptime n: usize) i32 {
|
||||
// mem[i] 记录爬到第 i 阶的方案总数,-1 代表无记录
|
||||
var mem = [_]i32{ -1 } ** (n + 1);
|
||||
return dfs(n, &mem);
|
||||
}
|
||||
|
||||
// Driver Code
|
||||
pub fn main() !void {
|
||||
comptime var n: usize = 9;
|
||||
|
||||
var res = climbingStairsDFSMem(n);
|
||||
std.debug.print("爬 {} 阶楼梯共有 {} 种方案\n", .{ n, res });
|
||||
|
||||
_ = try std.io.getStdIn().reader().readByte();
|
||||
}
|
||||
@@ -1,51 +0,0 @@
|
||||
// File: climbing_stairs_dp.zig
|
||||
// Created Time: 2023-07-15
|
||||
// Author: codingonion (coderonion@gmail.com)
|
||||
|
||||
const std = @import("std");
|
||||
|
||||
// 爬楼梯:动态规划
|
||||
fn climbingStairsDP(comptime n: usize) i32 {
|
||||
// 已知 dp[1] 和 dp[2] ,返回之
|
||||
if (n == 1 or n == 2) {
|
||||
return @intCast(n);
|
||||
}
|
||||
// 初始化 dp 表,用于存储子问题的解
|
||||
var dp = [_]i32{-1} ** (n + 1);
|
||||
// 初始状态:预设最小子问题的解
|
||||
dp[1] = 1;
|
||||
dp[2] = 2;
|
||||
// 状态转移:从较小子问题逐步求解较大子问题
|
||||
for (3..n + 1) |i| {
|
||||
dp[i] = dp[i - 1] + dp[i - 2];
|
||||
}
|
||||
return dp[n];
|
||||
}
|
||||
|
||||
// 爬楼梯:空间优化后的动态规划
|
||||
fn climbingStairsDPComp(comptime n: usize) i32 {
|
||||
if (n == 1 or n == 2) {
|
||||
return @intCast(n);
|
||||
}
|
||||
var a: i32 = 1;
|
||||
var b: i32 = 2;
|
||||
for (3..n + 1) |_| {
|
||||
var tmp = b;
|
||||
b = a + b;
|
||||
a = tmp;
|
||||
}
|
||||
return b;
|
||||
}
|
||||
|
||||
// Driver Code
|
||||
pub fn main() !void {
|
||||
comptime var n: usize = 9;
|
||||
|
||||
var res = climbingStairsDP(n);
|
||||
std.debug.print("爬 {} 阶楼梯共有 {} 种方案\n", .{ n, res });
|
||||
|
||||
res = climbingStairsDPComp(n);
|
||||
std.debug.print("爬 {} 阶楼梯共有 {} 种方案\n", .{ n, res });
|
||||
|
||||
_ = try std.io.getStdIn().reader().readByte();
|
||||
}
|
||||
@@ -1,77 +0,0 @@
|
||||
// File: coin_change.zig
|
||||
// Created Time: 2023-07-15
|
||||
// Author: codingonion (coderonion@gmail.com)
|
||||
|
||||
const std = @import("std");
|
||||
|
||||
// 零钱兑换:动态规划
|
||||
fn coinChangeDP(comptime coins: []i32, comptime amt: usize) i32 {
|
||||
comptime var n = coins.len;
|
||||
comptime var max = amt + 1;
|
||||
// 初始化 dp 表
|
||||
var dp = [_][amt + 1]i32{[_]i32{0} ** (amt + 1)} ** (n + 1);
|
||||
// 状态转移:首行首列
|
||||
for (1..amt + 1) |a| {
|
||||
dp[0][a] = max;
|
||||
}
|
||||
// 状态转移:其余行和列
|
||||
for (1..n + 1) |i| {
|
||||
for (1..amt + 1) |a| {
|
||||
if (coins[i - 1] > @as(i32, @intCast(a))) {
|
||||
// 若超过目标金额,则不选硬币 i
|
||||
dp[i][a] = dp[i - 1][a];
|
||||
} else {
|
||||
// 不选和选硬币 i 这两种方案的较小值
|
||||
dp[i][a] = @min(dp[i - 1][a], dp[i][a - @as(usize, @intCast(coins[i - 1]))] + 1);
|
||||
}
|
||||
}
|
||||
}
|
||||
if (dp[n][amt] != max) {
|
||||
return @intCast(dp[n][amt]);
|
||||
} else {
|
||||
return -1;
|
||||
}
|
||||
}
|
||||
|
||||
// 零钱兑换:空间优化后的动态规划
|
||||
fn coinChangeDPComp(comptime coins: []i32, comptime amt: usize) i32 {
|
||||
comptime var n = coins.len;
|
||||
comptime var max = amt + 1;
|
||||
// 初始化 dp 表
|
||||
var dp = [_]i32{0} ** (amt + 1);
|
||||
@memset(&dp, max);
|
||||
dp[0] = 0;
|
||||
// 状态转移
|
||||
for (1..n + 1) |i| {
|
||||
for (1..amt + 1) |a| {
|
||||
if (coins[i - 1] > @as(i32, @intCast(a))) {
|
||||
// 若超过目标金额,则不选硬币 i
|
||||
dp[a] = dp[a];
|
||||
} else {
|
||||
// 不选和选硬币 i 这两种方案的较小值
|
||||
dp[a] = @min(dp[a], dp[a - @as(usize, @intCast(coins[i - 1]))] + 1);
|
||||
}
|
||||
}
|
||||
}
|
||||
if (dp[amt] != max) {
|
||||
return @intCast(dp[amt]);
|
||||
} else {
|
||||
return -1;
|
||||
}
|
||||
}
|
||||
|
||||
// Driver Code
|
||||
pub fn main() !void {
|
||||
comptime var coins = [_]i32{ 1, 2, 5 };
|
||||
comptime var amt: usize = 4;
|
||||
|
||||
// 动态规划
|
||||
var res = coinChangeDP(&coins, amt);
|
||||
std.debug.print("凑到目标金额所需的最少硬币数量为 {}\n", .{res});
|
||||
|
||||
// 空间优化后的动态规划
|
||||
res = coinChangeDPComp(&coins, amt);
|
||||
std.debug.print("凑到目标金额所需的最少硬币数量为 {}\n", .{res});
|
||||
|
||||
_ = try std.io.getStdIn().reader().readByte();
|
||||
}
|
||||
@@ -1,66 +0,0 @@
|
||||
// File: coin_change_ii.zig
|
||||
// Created Time: 2023-07-15
|
||||
// Author: codingonion (coderonion@gmail.com)
|
||||
|
||||
const std = @import("std");
|
||||
|
||||
// 零钱兑换 II:动态规划
|
||||
fn coinChangeIIDP(comptime coins: []i32, comptime amt: usize) i32 {
|
||||
comptime var n = coins.len;
|
||||
// 初始化 dp 表
|
||||
var dp = [_][amt + 1]i32{[_]i32{0} ** (amt + 1)} ** (n + 1);
|
||||
// 初始化首列
|
||||
for (0..n + 1) |i| {
|
||||
dp[i][0] = 1;
|
||||
}
|
||||
// 状态转移
|
||||
for (1..n + 1) |i| {
|
||||
for (1..amt + 1) |a| {
|
||||
if (coins[i - 1] > @as(i32, @intCast(a))) {
|
||||
// 若超过目标金额,则不选硬币 i
|
||||
dp[i][a] = dp[i - 1][a];
|
||||
} else {
|
||||
// 不选和选硬币 i 这两种方案的较小值
|
||||
dp[i][a] = dp[i - 1][a] + dp[i][a - @as(usize, @intCast(coins[i - 1]))];
|
||||
}
|
||||
}
|
||||
}
|
||||
return dp[n][amt];
|
||||
}
|
||||
|
||||
// 零钱兑换 II:空间优化后的动态规划
|
||||
fn coinChangeIIDPComp(comptime coins: []i32, comptime amt: usize) i32 {
|
||||
comptime var n = coins.len;
|
||||
// 初始化 dp 表
|
||||
var dp = [_]i32{0} ** (amt + 1);
|
||||
dp[0] = 1;
|
||||
// 状态转移
|
||||
for (1..n + 1) |i| {
|
||||
for (1..amt + 1) |a| {
|
||||
if (coins[i - 1] > @as(i32, @intCast(a))) {
|
||||
// 若超过目标金额,则不选硬币 i
|
||||
dp[a] = dp[a];
|
||||
} else {
|
||||
// 不选和选硬币 i 这两种方案的较小值
|
||||
dp[a] = dp[a] + dp[a - @as(usize, @intCast(coins[i - 1]))];
|
||||
}
|
||||
}
|
||||
}
|
||||
return dp[amt];
|
||||
}
|
||||
|
||||
// Driver Code
|
||||
pub fn main() !void {
|
||||
comptime var coins = [_]i32{ 1, 2, 5 };
|
||||
comptime var amt: usize = 5;
|
||||
|
||||
// 动态规划
|
||||
var res = coinChangeIIDP(&coins, amt);
|
||||
std.debug.print("凑出目标金额的硬币组合数量为 {}\n", .{res});
|
||||
|
||||
// 空间优化后的动态规划
|
||||
res = coinChangeIIDPComp(&coins, amt);
|
||||
std.debug.print("凑出目标金额的硬币组合数量为 {}\n", .{res});
|
||||
|
||||
_ = try std.io.getStdIn().reader().readByte();
|
||||
}
|
||||
@@ -1,146 +0,0 @@
|
||||
// File: edit_distance.zig
|
||||
// Created Time: 2023-07-15
|
||||
// Author: codingonion (coderonion@gmail.com)
|
||||
|
||||
const std = @import("std");
|
||||
|
||||
// 编辑距离:暴力搜索
|
||||
fn editDistanceDFS(comptime s: []const u8, comptime t: []const u8, i: usize, j: usize) i32 {
|
||||
// 若 s 和 t 都为空,则返回 0
|
||||
if (i == 0 and j == 0) {
|
||||
return 0;
|
||||
}
|
||||
// 若 s 为空,则返回 t 长度
|
||||
if (i == 0) {
|
||||
return @intCast(j);
|
||||
}
|
||||
// 若 t 为空,则返回 s 长度
|
||||
if (j == 0) {
|
||||
return @intCast(i);
|
||||
}
|
||||
// 若两字符相等,则直接跳过此两字符
|
||||
if (s[i - 1] == t[j - 1]) {
|
||||
return editDistanceDFS(s, t, i - 1, j - 1);
|
||||
}
|
||||
// 最少编辑步数 = 插入、删除、替换这三种操作的最少编辑步数 + 1
|
||||
var insert = editDistanceDFS(s, t, i, j - 1);
|
||||
var delete = editDistanceDFS(s, t, i - 1, j);
|
||||
var replace = editDistanceDFS(s, t, i - 1, j - 1);
|
||||
// 返回最少编辑步数
|
||||
return @min(@min(insert, delete), replace) + 1;
|
||||
}
|
||||
|
||||
// 编辑距离:记忆化搜索
|
||||
fn editDistanceDFSMem(comptime s: []const u8, comptime t: []const u8, mem: anytype, i: usize, j: usize) i32 {
|
||||
// 若 s 和 t 都为空,则返回 0
|
||||
if (i == 0 and j == 0) {
|
||||
return 0;
|
||||
}
|
||||
// 若 s 为空,则返回 t 长度
|
||||
if (i == 0) {
|
||||
return @intCast(j);
|
||||
}
|
||||
// 若 t 为空,则返回 s 长度
|
||||
if (j == 0) {
|
||||
return @intCast(i);
|
||||
}
|
||||
// 若已有记录,则直接返回之
|
||||
if (mem[i][j] != -1) {
|
||||
return mem[i][j];
|
||||
}
|
||||
// 若两字符相等,则直接跳过此两字符
|
||||
if (s[i - 1] == t[j - 1]) {
|
||||
return editDistanceDFSMem(s, t, mem, i - 1, j - 1);
|
||||
}
|
||||
// 最少编辑步数 = 插入、删除、替换这三种操作的最少编辑步数 + 1
|
||||
var insert = editDistanceDFSMem(s, t, mem, i, j - 1);
|
||||
var delete = editDistanceDFSMem(s, t, mem, i - 1, j);
|
||||
var replace = editDistanceDFSMem(s, t, mem, i - 1, j - 1);
|
||||
// 记录并返回最少编辑步数
|
||||
mem[i][j] = @min(@min(insert, delete), replace) + 1;
|
||||
return mem[i][j];
|
||||
}
|
||||
|
||||
// 编辑距离:动态规划
|
||||
fn editDistanceDP(comptime s: []const u8, comptime t: []const u8) i32 {
|
||||
comptime var n = s.len;
|
||||
comptime var m = t.len;
|
||||
var dp = [_][m + 1]i32{[_]i32{0} ** (m + 1)} ** (n + 1);
|
||||
// 状态转移:首行首列
|
||||
for (1..n + 1) |i| {
|
||||
dp[i][0] = @intCast(i);
|
||||
}
|
||||
for (1..m + 1) |j| {
|
||||
dp[0][j] = @intCast(j);
|
||||
}
|
||||
// 状态转移:其余行和列
|
||||
for (1..n + 1) |i| {
|
||||
for (1..m + 1) |j| {
|
||||
if (s[i - 1] == t[j - 1]) {
|
||||
// 若两字符相等,则直接跳过此两字符
|
||||
dp[i][j] = dp[i - 1][j - 1];
|
||||
} else {
|
||||
// 最少编辑步数 = 插入、删除、替换这三种操作的最少编辑步数 + 1
|
||||
dp[i][j] = @min(@min(dp[i][j - 1], dp[i - 1][j]), dp[i - 1][j - 1]) + 1;
|
||||
}
|
||||
}
|
||||
}
|
||||
return dp[n][m];
|
||||
}
|
||||
|
||||
// 编辑距离:空间优化后的动态规划
|
||||
fn editDistanceDPComp(comptime s: []const u8, comptime t: []const u8) i32 {
|
||||
comptime var n = s.len;
|
||||
comptime var m = t.len;
|
||||
var dp = [_]i32{0} ** (m + 1);
|
||||
// 状态转移:首行
|
||||
for (1..m + 1) |j| {
|
||||
dp[j] = @intCast(j);
|
||||
}
|
||||
// 状态转移:其余行
|
||||
for (1..n + 1) |i| {
|
||||
// 状态转移:首列
|
||||
var leftup = dp[0]; // 暂存 dp[i-1, j-1]
|
||||
dp[0] = @intCast(i);
|
||||
// 状态转移:其余列
|
||||
for (1..m + 1) |j| {
|
||||
var temp = dp[j];
|
||||
if (s[i - 1] == t[j - 1]) {
|
||||
// 若两字符相等,则直接跳过此两字符
|
||||
dp[j] = leftup;
|
||||
} else {
|
||||
// 最少编辑步数 = 插入、删除、替换这三种操作的最少编辑步数 + 1
|
||||
dp[j] = @min(@min(dp[j - 1], dp[j]), leftup) + 1;
|
||||
}
|
||||
leftup = temp; // 更新为下一轮的 dp[i-1, j-1]
|
||||
}
|
||||
}
|
||||
return dp[m];
|
||||
}
|
||||
|
||||
// Driver Code
|
||||
pub fn main() !void {
|
||||
const s = "bag";
|
||||
const t = "pack";
|
||||
comptime var n = s.len;
|
||||
comptime var m = t.len;
|
||||
|
||||
// 暴力搜索
|
||||
var res = editDistanceDFS(s, t, n, m);
|
||||
std.debug.print("将 {s} 更改为 {s} 最少需要编辑 {} 步\n", .{ s, t, res });
|
||||
|
||||
// 记忆搜索
|
||||
var mem = [_][m + 1]i32{[_]i32{-1} ** (m + 1)} ** (n + 1);
|
||||
res = editDistanceDFSMem(s, t, @constCast(&mem), n, m);
|
||||
std.debug.print("将 {s} 更改为 {s} 最少需要编辑 {} 步\n", .{ s, t, res });
|
||||
|
||||
// 动态规划
|
||||
res = editDistanceDP(s, t);
|
||||
std.debug.print("将 {s} 更改为 {s} 最少需要编辑 {} 步\n", .{ s, t, res });
|
||||
|
||||
// 空间优化后的动态规划
|
||||
res = editDistanceDPComp(s, t);
|
||||
std.debug.print("将 {s} 更改为 {s} 最少需要编辑 {} 步\n", .{ s, t, res });
|
||||
|
||||
_ = try std.io.getStdIn().reader().readByte();
|
||||
}
|
||||
@@ -1,110 +0,0 @@
|
||||
// File: knapsack.zig
|
||||
// Created Time: 2023-07-15
|
||||
// Author: codingonion (coderonion@gmail.com)
|
||||
|
||||
const std = @import("std");
|
||||
|
||||
// 0-1 背包:暴力搜索
|
||||
fn knapsackDFS(wgt: []i32, val: []i32, i: usize, c: usize) i32 {
|
||||
// 若已选完所有物品或背包无剩余容量,则返回价值 0
|
||||
if (i == 0 or c == 0) {
|
||||
return 0;
|
||||
}
|
||||
// 若超过背包容量,则只能选择不放入背包
|
||||
if (wgt[i - 1] > c) {
|
||||
return knapsackDFS(wgt, val, i - 1, c);
|
||||
}
|
||||
// 计算不放入和放入物品 i 的最大价值
|
||||
var no = knapsackDFS(wgt, val, i - 1, c);
|
||||
var yes = knapsackDFS(wgt, val, i - 1, c - @as(usize, @intCast(wgt[i - 1]))) + val[i - 1];
|
||||
// 返回两种方案中价值更大的那一个
|
||||
return @max(no, yes);
|
||||
}
|
||||
|
||||
// 0-1 背包:记忆化搜索
|
||||
fn knapsackDFSMem(wgt: []i32, val: []i32, mem: anytype, i: usize, c: usize) i32 {
|
||||
// 若已选完所有物品或背包无剩余容量,则返回价值 0
|
||||
if (i == 0 or c == 0) {
|
||||
return 0;
|
||||
}
|
||||
// 若已有记录,则直接返回
|
||||
if (mem[i][c] != -1) {
|
||||
return mem[i][c];
|
||||
}
|
||||
// 若超过背包容量,则只能选择不放入背包
|
||||
if (wgt[i - 1] > c) {
|
||||
return knapsackDFSMem(wgt, val, mem, i - 1, c);
|
||||
}
|
||||
// 计算不放入和放入物品 i 的最大价值
|
||||
var no = knapsackDFSMem(wgt, val, mem, i - 1, c);
|
||||
var yes = knapsackDFSMem(wgt, val, mem, i - 1, c - @as(usize, @intCast(wgt[i - 1]))) + val[i - 1];
|
||||
// 记录并返回两种方案中价值更大的那一个
|
||||
mem[i][c] = @max(no, yes);
|
||||
return mem[i][c];
|
||||
}
|
||||
|
||||
// 0-1 背包:动态规划
|
||||
fn knapsackDP(comptime wgt: []i32, val: []i32, comptime cap: usize) i32 {
|
||||
comptime var n = wgt.len;
|
||||
// 初始化 dp 表
|
||||
var dp = [_][cap + 1]i32{[_]i32{0} ** (cap + 1)} ** (n + 1);
|
||||
// 状态转移
|
||||
for (1..n + 1) |i| {
|
||||
for (1..cap + 1) |c| {
|
||||
if (wgt[i - 1] > c) {
|
||||
// 若超过背包容量,则不选物品 i
|
||||
dp[i][c] = dp[i - 1][c];
|
||||
} else {
|
||||
// 不选和选物品 i 这两种方案的较大值
|
||||
dp[i][c] = @max(dp[i - 1][c], dp[i - 1][c - @as(usize, @intCast(wgt[i - 1]))] + val[i - 1]);
|
||||
}
|
||||
}
|
||||
}
|
||||
return dp[n][cap];
|
||||
}
|
||||
|
||||
// 0-1 背包:空间优化后的动态规划
|
||||
fn knapsackDPComp(wgt: []i32, val: []i32, comptime cap: usize) i32 {
|
||||
var n = wgt.len;
|
||||
// 初始化 dp 表
|
||||
var dp = [_]i32{0} ** (cap + 1);
|
||||
// 状态转移
|
||||
for (1..n + 1) |i| {
|
||||
// 倒序遍历
|
||||
var c = cap;
|
||||
while (c > 0) : (c -= 1) {
|
||||
if (wgt[i - 1] < c) {
|
||||
// 不选和选物品 i 这两种方案的较大值
|
||||
dp[c] = @max(dp[c], dp[c - @as(usize, @intCast(wgt[i - 1]))] + val[i - 1]);
|
||||
}
|
||||
}
|
||||
}
|
||||
return dp[cap];
|
||||
}
|
||||
|
||||
// Driver Code
|
||||
pub fn main() !void {
|
||||
comptime var wgt = [_]i32{ 10, 20, 30, 40, 50 };
|
||||
comptime var val = [_]i32{ 50, 120, 150, 210, 240 };
|
||||
comptime var cap = 50;
|
||||
comptime var n = wgt.len;
|
||||
|
||||
// 暴力搜索
|
||||
var res = knapsackDFS(&wgt, &val, n, cap);
|
||||
std.debug.print("不超过背包容量的最大物品价值为 {}\n", .{res});
|
||||
|
||||
// 记忆搜索
|
||||
var mem = [_][cap + 1]i32{[_]i32{-1} ** (cap + 1)} ** (n + 1);
|
||||
res = knapsackDFSMem(&wgt, &val, @constCast(&mem), n, cap);
|
||||
std.debug.print("不超过背包容量的最大物品价值为 {}\n", .{res});
|
||||
|
||||
// 动态规划
|
||||
res = knapsackDP(&wgt, &val, cap);
|
||||
std.debug.print("不超过背包容量的最大物品价值为 {}\n", .{res});
|
||||
|
||||
// 空间优化后的动态规划
|
||||
res = knapsackDPComp(&wgt, &val, cap);
|
||||
std.debug.print("不超过背包容量的最大物品价值为 {}\n", .{res});
|
||||
|
||||
_ = try std.io.getStdIn().reader().readByte();
|
||||
}
|
||||
@@ -1,54 +0,0 @@
|
||||
// File: min_cost_climbing_stairs_dp.zig
|
||||
// Created Time: 2023-07-15
|
||||
// Author: codingonion (coderonion@gmail.com)
|
||||
|
||||
const std = @import("std");
|
||||
|
||||
// 爬楼梯最小代价:动态规划
|
||||
fn minCostClimbingStairsDP(comptime cost: []i32) i32 {
|
||||
comptime var n = cost.len - 1;
|
||||
if (n == 1 or n == 2) {
|
||||
return cost[n];
|
||||
}
|
||||
// 初始化 dp 表,用于存储子问题的解
|
||||
var dp = [_]i32{-1} ** (n + 1);
|
||||
// 初始状态:预设最小子问题的解
|
||||
dp[1] = cost[1];
|
||||
dp[2] = cost[2];
|
||||
// 状态转移:从较小子问题逐步求解较大子问题
|
||||
for (3..n + 1) |i| {
|
||||
dp[i] = @min(dp[i - 1], dp[i - 2]) + cost[i];
|
||||
}
|
||||
return dp[n];
|
||||
}
|
||||
|
||||
// 爬楼梯最小代价:空间优化后的动态规划
|
||||
fn minCostClimbingStairsDPComp(cost: []i32) i32 {
|
||||
var n = cost.len - 1;
|
||||
if (n == 1 or n == 2) {
|
||||
return cost[n];
|
||||
}
|
||||
var a = cost[1];
|
||||
var b = cost[2];
|
||||
// 状态转移:从较小子问题逐步求解较大子问题
|
||||
for (3..n + 1) |i| {
|
||||
var tmp = b;
|
||||
b = @min(a, tmp) + cost[i];
|
||||
a = tmp;
|
||||
}
|
||||
return b;
|
||||
}
|
||||
|
||||
// Driver Code
|
||||
pub fn main() !void {
|
||||
comptime var cost = [_]i32{ 0, 1, 10, 1, 1, 1, 10, 1, 1, 10, 1 };
|
||||
std.debug.print("输入楼梯的代价列表为 {any}\n", .{cost});
|
||||
|
||||
var res = minCostClimbingStairsDP(&cost);
|
||||
std.debug.print("输入楼梯的代价列表为 {}\n", .{res});
|
||||
|
||||
res = minCostClimbingStairsDPComp(&cost);
|
||||
std.debug.print("输入楼梯的代价列表为 {}\n", .{res});
|
||||
|
||||
_ = try std.io.getStdIn().reader().readByte();
|
||||
}
|
||||
@@ -1,122 +0,0 @@
|
||||
// File: min_path_sum.zig
|
||||
// Created Time: 2023-07-15
|
||||
// Author: codingonion (coderonion@gmail.com)
|
||||
|
||||
const std = @import("std");
|
||||
|
||||
// 最小路径和:暴力搜索
|
||||
fn minPathSumDFS(grid: anytype, i: i32, j: i32) i32 {
|
||||
// 若为左上角单元格,则终止搜索
|
||||
if (i == 0 and j == 0) {
|
||||
return grid[0][0];
|
||||
}
|
||||
// 若行列索引越界,则返回 +∞ 代价
|
||||
if (i < 0 or j < 0) {
|
||||
return std.math.maxInt(i32);
|
||||
}
|
||||
// 计算从左上角到 (i-1, j) 和 (i, j-1) 的最小路径代价
|
||||
var up = minPathSumDFS(grid, i - 1, j);
|
||||
var left = minPathSumDFS(grid, i, j - 1);
|
||||
// 返回从左上角到 (i, j) 的最小路径代价
|
||||
return @min(left, up) + grid[@as(usize, @intCast(i))][@as(usize, @intCast(j))];
|
||||
}
|
||||
|
||||
// 最小路径和:记忆化搜索
|
||||
fn minPathSumDFSMem(grid: anytype, mem: anytype, i: i32, j: i32) i32 {
|
||||
// 若为左上角单元格,则终止搜索
|
||||
if (i == 0 and j == 0) {
|
||||
return grid[0][0];
|
||||
}
|
||||
// 若行列索引越界,则返回 +∞ 代价
|
||||
if (i < 0 or j < 0) {
|
||||
return std.math.maxInt(i32);
|
||||
}
|
||||
// 若已有记录,则直接返回
|
||||
if (mem[@as(usize, @intCast(i))][@as(usize, @intCast(j))] != -1) {
|
||||
return mem[@as(usize, @intCast(i))][@as(usize, @intCast(j))];
|
||||
}
|
||||
// 计算从左上角到 (i-1, j) 和 (i, j-1) 的最小路径代价
|
||||
var up = minPathSumDFSMem(grid, mem, i - 1, j);
|
||||
var left = minPathSumDFSMem(grid, mem, i, j - 1);
|
||||
// 返回从左上角到 (i, j) 的最小路径代价
|
||||
// 记录并返回左上角到 (i, j) 的最小路径代价
|
||||
mem[@as(usize, @intCast(i))][@as(usize, @intCast(j))] = @min(left, up) + grid[@as(usize, @intCast(i))][@as(usize, @intCast(j))];
|
||||
return mem[@as(usize, @intCast(i))][@as(usize, @intCast(j))];
|
||||
}
|
||||
|
||||
// 最小路径和:动态规划
|
||||
fn minPathSumDP(comptime grid: anytype) i32 {
|
||||
comptime var n = grid.len;
|
||||
comptime var m = grid[0].len;
|
||||
// 初始化 dp 表
|
||||
var dp = [_][m]i32{[_]i32{0} ** m} ** n;
|
||||
dp[0][0] = grid[0][0];
|
||||
// 状态转移:首行
|
||||
for (1..m) |j| {
|
||||
dp[0][j] = dp[0][j - 1] + grid[0][j];
|
||||
}
|
||||
// 状态转移:首列
|
||||
for (1..n) |i| {
|
||||
dp[i][0] = dp[i - 1][0] + grid[i][0];
|
||||
}
|
||||
// 状态转移:其余行和列
|
||||
for (1..n) |i| {
|
||||
for (1..m) |j| {
|
||||
dp[i][j] = @min(dp[i][j - 1], dp[i - 1][j]) + grid[i][j];
|
||||
}
|
||||
}
|
||||
return dp[n - 1][m - 1];
|
||||
}
|
||||
|
||||
// 最小路径和:空间优化后的动态规划
|
||||
fn minPathSumDPComp(comptime grid: anytype) i32 {
|
||||
comptime var n = grid.len;
|
||||
comptime var m = grid[0].len;
|
||||
// 初始化 dp 表
|
||||
var dp = [_]i32{0} ** m;
|
||||
// 状态转移:首行
|
||||
dp[0] = grid[0][0];
|
||||
for (1..m) |j| {
|
||||
dp[j] = dp[j - 1] + grid[0][j];
|
||||
}
|
||||
// 状态转移:其余行
|
||||
for (1..n) |i| {
|
||||
// 状态转移:首列
|
||||
dp[0] = dp[0] + grid[i][0];
|
||||
for (1..m) |j| {
|
||||
dp[j] = @min(dp[j - 1], dp[j]) + grid[i][j];
|
||||
}
|
||||
}
|
||||
return dp[m - 1];
|
||||
}
|
||||
|
||||
// Driver Code
|
||||
pub fn main() !void {
|
||||
comptime var grid = [_][4]i32{
|
||||
[_]i32{ 1, 3, 1, 5 },
|
||||
[_]i32{ 2, 2, 4, 2 },
|
||||
[_]i32{ 5, 3, 2, 1 },
|
||||
[_]i32{ 4, 3, 5, 2 },
|
||||
};
|
||||
comptime var n = grid.len;
|
||||
comptime var m = grid[0].len;
|
||||
|
||||
// 暴力搜索
|
||||
var res = minPathSumDFS(&grid, n - 1, m - 1);
|
||||
std.debug.print("从左上角到右下角的最小路径和为 {}\n", .{res});
|
||||
|
||||
// 记忆化搜索
|
||||
var mem = [_][m]i32{[_]i32{-1} ** m} ** n;
|
||||
res = minPathSumDFSMem(&grid, &mem, n - 1, m - 1);
|
||||
std.debug.print("从左上角到右下角的最小路径和为 {}\n", .{res});
|
||||
|
||||
// 动态规划
|
||||
res = minPathSumDP(&grid);
|
||||
std.debug.print("从左上角到右下角的最小路径和为 {}\n", .{res});
|
||||
|
||||
// 空间优化后的动态规划
|
||||
res = minPathSumDPComp(&grid);
|
||||
std.debug.print("从左上角到右下角的最小路径和为 {}\n", .{res});
|
||||
|
||||
_ = try std.io.getStdIn().reader().readByte();
|
||||
}
|
||||
@@ -1,62 +0,0 @@
|
||||
// File: unbounded_knapsack.zig
|
||||
// Created Time: 2023-07-15
|
||||
// Author: codingonion (coderonion@gmail.com)
|
||||
|
||||
const std = @import("std");
|
||||
|
||||
// 完全背包:动态规划
|
||||
fn unboundedKnapsackDP(comptime wgt: []i32, val: []i32, comptime cap: usize) i32 {
|
||||
comptime var n = wgt.len;
|
||||
// 初始化 dp 表
|
||||
var dp = [_][cap + 1]i32{[_]i32{0} ** (cap + 1)} ** (n + 1);
|
||||
// 状态转移
|
||||
for (1..n + 1) |i| {
|
||||
for (1..cap + 1) |c| {
|
||||
if (wgt[i - 1] > c) {
|
||||
// 若超过背包容量,则不选物品 i
|
||||
dp[i][c] = dp[i - 1][c];
|
||||
} else {
|
||||
// 不选和选物品 i 这两种方案的较大值
|
||||
dp[i][c] = @max(dp[i - 1][c], dp[i][c - @as(usize, @intCast(wgt[i - 1]))] + val[i - 1]);
|
||||
}
|
||||
}
|
||||
}
|
||||
return dp[n][cap];
|
||||
}
|
||||
|
||||
// 完全背包:空间优化后的动态规划
|
||||
fn unboundedKnapsackDPComp(comptime wgt: []i32, val: []i32, comptime cap: usize) i32 {
|
||||
comptime var n = wgt.len;
|
||||
// 初始化 dp 表
|
||||
var dp = [_]i32{0} ** (cap + 1);
|
||||
// 状态转移
|
||||
for (1..n + 1) |i| {
|
||||
for (1..cap + 1) |c| {
|
||||
if (wgt[i - 1] > c) {
|
||||
// 若超过背包容量,则不选物品 i
|
||||
dp[c] = dp[c];
|
||||
} else {
|
||||
// 不选和选物品 i 这两种方案的较大值
|
||||
dp[c] = @max(dp[c], dp[c - @as(usize, @intCast(wgt[i - 1]))] + val[i - 1]);
|
||||
}
|
||||
}
|
||||
}
|
||||
return dp[cap];
|
||||
}
|
||||
|
||||
// Driver Code
|
||||
pub fn main() !void {
|
||||
comptime var wgt = [_]i32{ 1, 2, 3 };
|
||||
comptime var val = [_]i32{ 5, 11, 15 };
|
||||
comptime var cap = 4;
|
||||
|
||||
// 动态规划
|
||||
var res = unboundedKnapsackDP(&wgt, &val, cap);
|
||||
std.debug.print("不超过背包容量的最大物品价值为 {}\n", .{res});
|
||||
|
||||
// 空间优化后的动态规划
|
||||
res = unboundedKnapsackDPComp(&wgt, &val, cap);
|
||||
std.debug.print("不超过背包容量的最大物品价值为 {}\n", .{res});
|
||||
|
||||
_ = try std.io.getStdIn().reader().readByte();
|
||||
}
|
||||
@@ -1,162 +0,0 @@
|
||||
// File: array_hash_map.zig
|
||||
// Created Time: 2023-01-15
|
||||
// Author: codingonion (coderonion@gmail.com)
|
||||
|
||||
const std = @import("std");
|
||||
const inc = @import("include");
|
||||
|
||||
// 键值对
|
||||
const Pair = struct {
|
||||
key: usize = undefined,
|
||||
val: []const u8 = undefined,
|
||||
|
||||
pub fn init(key: usize, val: []const u8) Pair {
|
||||
return Pair {
|
||||
.key = key,
|
||||
.val = val,
|
||||
};
|
||||
}
|
||||
};
|
||||
|
||||
// 基于数组实现的哈希表
|
||||
pub 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 = Pair.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 pairSet(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.pairSet();
|
||||
defer entry_set.deinit();
|
||||
for (entry_set.items) |item| {
|
||||
std.debug.print("{} -> {s}\n", .{item.key, item.val});
|
||||
}
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
// Driver Code
|
||||
pub fn main() !void {
|
||||
// 初始化哈希表
|
||||
var map = ArrayHashMap(Pair){};
|
||||
try map.init(std.heap.page_allocator);
|
||||
defer map.deinit();
|
||||
|
||||
// 添加操作
|
||||
// 在哈希表中添加键值对 (key, value)
|
||||
try map.put(12836, "小哈");
|
||||
try map.put(15937, "小啰");
|
||||
try map.put(16750, "小算");
|
||||
try map.put(13276, "小法");
|
||||
try map.put(10583, "小鸭");
|
||||
std.debug.print("\n添加完成后,哈希表为\nKey -> Value\n", .{});
|
||||
try map.print();
|
||||
|
||||
// 查询操作
|
||||
// 向哈希表中输入键 key ,得到值 value
|
||||
var name = map.get(15937);
|
||||
std.debug.print("\n输入学号 15937 ,查询到姓名 {s}\n", .{name});
|
||||
|
||||
// 删除操作
|
||||
// 在哈希表中删除键值对 (key, value)
|
||||
try map.remove(10583);
|
||||
std.debug.print("\n删除 10583 后,哈希表为\nKey -> Value\n", .{});
|
||||
try map.print();
|
||||
|
||||
// 遍历哈希表
|
||||
std.debug.print("\n遍历键值对 Key->Value\n", .{});
|
||||
var entry_set = try map.pairSet();
|
||||
for (entry_set.items) |kv| {
|
||||
std.debug.print("{} -> {s}\n", .{kv.key, kv.val});
|
||||
}
|
||||
defer entry_set.deinit();
|
||||
std.debug.print("\n单独遍历键 Key\n", .{});
|
||||
var key_set = try map.keySet();
|
||||
for (key_set.items) |key| {
|
||||
std.debug.print("{}\n", .{key});
|
||||
}
|
||||
defer key_set.deinit();
|
||||
std.debug.print("\n单独遍历值 value\n", .{});
|
||||
var value_set = try map.valueSet();
|
||||
for (value_set.items) |val| {
|
||||
std.debug.print("{s}\n", .{val});
|
||||
}
|
||||
defer value_set.deinit();
|
||||
|
||||
_ = try std.io.getStdIn().reader().readByte();
|
||||
}
|
||||
@@ -1,54 +0,0 @@
|
||||
// File: hash_map.zig
|
||||
// Created Time: 2023-01-13
|
||||
// Author: codingonion (coderonion@gmail.com)
|
||||
|
||||
const std = @import("std");
|
||||
const inc = @import("include");
|
||||
|
||||
// Driver Code
|
||||
pub fn main() !void {
|
||||
// 初始化哈希表
|
||||
var map = std.AutoHashMap(i32, []const u8).init(std.heap.page_allocator);
|
||||
// 延迟释放内存
|
||||
defer map.deinit();
|
||||
|
||||
// 添加操作
|
||||
// 在哈希表中添加键值对 (key, value)
|
||||
try map.put(12836, "小哈");
|
||||
try map.put(15937, "小啰");
|
||||
try map.put(16750, "小算");
|
||||
try map.put(13276, "小法");
|
||||
try map.put(10583, "小鸭");
|
||||
std.debug.print("\n添加完成后,哈希表为\nKey -> Value\n", .{});
|
||||
inc.PrintUtil.printHashMap(i32, []const u8, map);
|
||||
|
||||
// 查询操作
|
||||
// 向哈希表中输入键 key ,得到值 value
|
||||
var name = map.get(15937).?;
|
||||
std.debug.print("\n输入学号 15937 ,查询到姓名 {s}\n", .{name});
|
||||
|
||||
// 删除操作
|
||||
// 在哈希表中删除键值对 (key, value)
|
||||
_ = map.remove(10583);
|
||||
std.debug.print("\n删除 10583 后,哈希表为\nKey -> Value\n", .{});
|
||||
inc.PrintUtil.printHashMap(i32, []const u8, map);
|
||||
|
||||
// 遍历哈希表
|
||||
std.debug.print("\n遍历键值对 Key->Value\n", .{});
|
||||
inc.PrintUtil.printHashMap(i32, []const u8, map);
|
||||
|
||||
std.debug.print("\n单独遍历键 Key\n", .{});
|
||||
var it = map.iterator();
|
||||
while (it.next()) |kv| {
|
||||
std.debug.print("{}\n", .{kv.key_ptr.*});
|
||||
}
|
||||
|
||||
std.debug.print("\n单独遍历值 value\n", .{});
|
||||
it = map.iterator();
|
||||
while (it.next()) |kv| {
|
||||
std.debug.print("{s}\n", .{kv.value_ptr.*});
|
||||
}
|
||||
|
||||
_ = try std.io.getStdIn().reader().readByte();
|
||||
}
|
||||
|
||||
@@ -1,80 +0,0 @@
|
||||
// File: heap.zig
|
||||
// Created Time: 2023-01-14
|
||||
// Author: codingonion (coderonion@gmail.com)
|
||||
|
||||
const std = @import("std");
|
||||
const inc = @import("include");
|
||||
|
||||
fn lessThan(context: void, a: i32, b: i32) std.math.Order {
|
||||
_ = context;
|
||||
return std.math.order(a, b);
|
||||
}
|
||||
|
||||
fn greaterThan(context: void, a: i32, b: i32) std.math.Order {
|
||||
return lessThan(context, a, b).invert();
|
||||
}
|
||||
|
||||
fn testPush(comptime T: type, mem_allocator: std.mem.Allocator, heap: anytype, val: T) !void {
|
||||
try heap.add(val); //元素入堆
|
||||
std.debug.print("\n元素 {} 入堆后\n", .{val});
|
||||
try inc.PrintUtil.printHeap(T, mem_allocator, heap);
|
||||
}
|
||||
|
||||
fn testPop(comptime T: type, mem_allocator: std.mem.Allocator, heap: anytype) !void {
|
||||
var val = heap.remove(); //堆顶元素出堆
|
||||
std.debug.print("\n堆顶元素 {} 出堆后\n", .{val});
|
||||
try inc.PrintUtil.printHeap(T, mem_allocator, heap);
|
||||
}
|
||||
|
||||
// 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();
|
||||
|
||||
// 初始化堆
|
||||
// 初始化小顶堆
|
||||
const PQlt = std.PriorityQueue(i32, void, lessThan);
|
||||
var min_heap = PQlt.init(std.heap.page_allocator, {});
|
||||
defer min_heap.deinit();
|
||||
// 初始化大顶堆
|
||||
const PQgt = std.PriorityQueue(i32, void, greaterThan);
|
||||
var max_heap = PQgt.init(std.heap.page_allocator, {});
|
||||
defer max_heap.deinit();
|
||||
|
||||
std.debug.print("\n以下测试样例为大顶堆", .{});
|
||||
|
||||
// 元素入堆
|
||||
try testPush(i32, mem_allocator, &max_heap, 1);
|
||||
try testPush(i32, mem_allocator, &max_heap, 3);
|
||||
try testPush(i32, mem_allocator, &max_heap, 2);
|
||||
try testPush(i32, mem_allocator, &max_heap, 5);
|
||||
try testPush(i32, mem_allocator, &max_heap, 4);
|
||||
|
||||
// 获取堆顶元素
|
||||
var peek = max_heap.peek().?;
|
||||
std.debug.print("\n堆顶元素为 {}\n", .{peek});
|
||||
|
||||
// 堆顶元素出堆
|
||||
try testPop(i32, mem_allocator, &max_heap);
|
||||
try testPop(i32, mem_allocator, &max_heap);
|
||||
try testPop(i32, mem_allocator, &max_heap);
|
||||
try testPop(i32, mem_allocator, &max_heap);
|
||||
try testPop(i32, mem_allocator, &max_heap);
|
||||
|
||||
// 获取堆的大小
|
||||
var size = max_heap.len;
|
||||
std.debug.print("\n堆元素数量为 {}\n", .{size});
|
||||
|
||||
// 判断堆是否为空
|
||||
var is_empty = if (max_heap.len == 0) true else false;
|
||||
std.debug.print("\n堆是否为空 {}\n", .{is_empty});
|
||||
|
||||
// 输入列表并建堆
|
||||
try min_heap.addSlice(&[_]i32{ 1, 3, 2, 5, 4 });
|
||||
std.debug.print("\n输入列表并建立小顶堆后\n", .{});
|
||||
try inc.PrintUtil.printHeap(i32, mem_allocator, min_heap);
|
||||
|
||||
_ = try std.io.getStdIn().reader().readByte();
|
||||
}
|
||||
@@ -1,186 +0,0 @@
|
||||
// File: my_heap.zig
|
||||
// Created Time: 2023-01-14
|
||||
// Author: codingonion (coderonion@gmail.com)
|
||||
|
||||
const std = @import("std");
|
||||
const inc = @import("include");
|
||||
|
||||
// 堆类简易实现
|
||||
pub fn MaxHeap(comptime T: type) type {
|
||||
return struct {
|
||||
const Self = @This();
|
||||
|
||||
max_heap: ?std.ArrayList(T) = null, // 使用列表而非数组,这样无须考虑扩容问题
|
||||
|
||||
// 构造方法,根据输入列表建堆
|
||||
pub fn init(self: *Self, allocator: std.mem.Allocator, nums: []const T) !void {
|
||||
if (self.max_heap != null) return;
|
||||
self.max_heap = std.ArrayList(T).init(allocator);
|
||||
// 将列表元素原封不动添加进堆
|
||||
try self.max_heap.?.appendSlice(nums);
|
||||
// 堆化除叶节点以外的其他所有节点
|
||||
var i: usize = parent(self.size() - 1) + 1;
|
||||
while (i > 0) : (i -= 1) {
|
||||
try self.siftDown(i - 1);
|
||||
}
|
||||
}
|
||||
|
||||
// 析构方法,释放内存
|
||||
pub fn deinit(self: *Self) void {
|
||||
if (self.max_heap != null) self.max_heap.?.deinit();
|
||||
}
|
||||
|
||||
// 获取左子节点的索引
|
||||
fn left(i: usize) usize {
|
||||
return 2 * i + 1;
|
||||
}
|
||||
|
||||
// 获取右子节点的索引
|
||||
fn right(i: usize) usize {
|
||||
return 2 * i + 2;
|
||||
}
|
||||
|
||||
// 获取父节点的索引
|
||||
fn parent(i: usize) usize {
|
||||
// return (i - 1) / 2; // 向下整除
|
||||
return @divFloor(i - 1, 2);
|
||||
}
|
||||
|
||||
// 交换元素
|
||||
fn swap(self: *Self, i: usize, j: usize) !void {
|
||||
var tmp = self.max_heap.?.items[i];
|
||||
try self.max_heap.?.replaceRange(i, 1, &[_]T{self.max_heap.?.items[j]});
|
||||
try self.max_heap.?.replaceRange(j, 1, &[_]T{tmp});
|
||||
}
|
||||
|
||||
// 获取堆大小
|
||||
pub fn size(self: *Self) usize {
|
||||
return self.max_heap.?.items.len;
|
||||
}
|
||||
|
||||
// 判断堆是否为空
|
||||
pub fn isEmpty(self: *Self) bool {
|
||||
return self.size() == 0;
|
||||
}
|
||||
|
||||
// 访问堆顶元素
|
||||
pub fn peek(self: *Self) T {
|
||||
return self.max_heap.?.items[0];
|
||||
}
|
||||
|
||||
// 元素入堆
|
||||
pub fn push(self: *Self, val: T) !void {
|
||||
// 添加节点
|
||||
try self.max_heap.?.append(val);
|
||||
// 从底至顶堆化
|
||||
try self.siftUp(self.size() - 1);
|
||||
}
|
||||
|
||||
// 从节点 i 开始,从底至顶堆化
|
||||
fn siftUp(self: *Self, i_: usize) !void {
|
||||
var i = i_;
|
||||
while (true) {
|
||||
// 获取节点 i 的父节点
|
||||
var p = parent(i);
|
||||
// 当“越过根节点”或“节点无须修复”时,结束堆化
|
||||
if (p < 0 or self.max_heap.?.items[i] <= self.max_heap.?.items[p]) break;
|
||||
// 交换两节点
|
||||
try self.swap(i, p);
|
||||
// 循环向上堆化
|
||||
i = p;
|
||||
}
|
||||
}
|
||||
|
||||
// 元素出堆
|
||||
pub fn pop(self: *Self) !T {
|
||||
// 判断处理
|
||||
if (self.isEmpty()) unreachable;
|
||||
// 交换根节点与最右叶节点(交换首元素与尾元素)
|
||||
try self.swap(0, self.size() - 1);
|
||||
// 删除节点
|
||||
var val = self.max_heap.?.pop();
|
||||
// 从顶至底堆化
|
||||
try self.siftDown(0);
|
||||
// 返回堆顶元素
|
||||
return val;
|
||||
}
|
||||
|
||||
// 从节点 i 开始,从顶至底堆化
|
||||
fn siftDown(self: *Self, i_: usize) !void {
|
||||
var i = i_;
|
||||
while (true) {
|
||||
// 判断节点 i, l, r 中值最大的节点,记为 ma
|
||||
var l = left(i);
|
||||
var r = right(i);
|
||||
var ma = i;
|
||||
if (l < self.size() and self.max_heap.?.items[l] > self.max_heap.?.items[ma]) ma = l;
|
||||
if (r < self.size() and self.max_heap.?.items[r] > self.max_heap.?.items[ma]) ma = r;
|
||||
// 若节点 i 最大或索引 l, r 越界,则无须继续堆化,跳出
|
||||
if (ma == i) break;
|
||||
// 交换两节点
|
||||
try self.swap(i, ma);
|
||||
// 循环向下堆化
|
||||
i = ma;
|
||||
}
|
||||
}
|
||||
|
||||
fn lessThan(context: void, a: T, b: T) std.math.Order {
|
||||
_ = context;
|
||||
return std.math.order(a, b);
|
||||
}
|
||||
|
||||
fn greaterThan(context: void, a: T, b: T) std.math.Order {
|
||||
return lessThan(context, a, b).invert();
|
||||
}
|
||||
|
||||
// 打印堆(二叉树)
|
||||
pub fn print(self: *Self, mem_allocator: std.mem.Allocator) !void {
|
||||
const PQgt = std.PriorityQueue(T, void, greaterThan);
|
||||
var queue = PQgt.init(std.heap.page_allocator, {});
|
||||
defer queue.deinit();
|
||||
try queue.addSlice(self.max_heap.?.items);
|
||||
try inc.PrintUtil.printHeap(T, mem_allocator, queue);
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
// 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();
|
||||
|
||||
// 初始化大顶堆
|
||||
var max_heap = MaxHeap(i32){};
|
||||
try max_heap.init(std.heap.page_allocator, &[_]i32{ 9, 8, 6, 6, 7, 5, 2, 1, 4, 3, 6, 2 });
|
||||
defer max_heap.deinit();
|
||||
std.debug.print("\n输入列表并建堆后\n", .{});
|
||||
try max_heap.print(mem_allocator);
|
||||
|
||||
// 获取堆顶元素
|
||||
var peek = max_heap.peek();
|
||||
std.debug.print("\n堆顶元素为 {}\n", .{peek});
|
||||
|
||||
// 元素入堆
|
||||
const val = 7;
|
||||
try max_heap.push(val);
|
||||
std.debug.print("\n元素 {} 入堆后\n", .{val});
|
||||
try max_heap.print(mem_allocator);
|
||||
|
||||
// 堆顶元素出堆
|
||||
peek = try max_heap.pop();
|
||||
std.debug.print("\n堆顶元素 {} 出堆后\n", .{peek});
|
||||
try max_heap.print(mem_allocator);
|
||||
|
||||
// 获取堆的大小
|
||||
var size = max_heap.size();
|
||||
std.debug.print("\n堆元素数量为 {}", .{size});
|
||||
|
||||
// 判断堆是否为空
|
||||
var is_empty = max_heap.isEmpty();
|
||||
std.debug.print("\n堆是否为空 {}\n", .{is_empty});
|
||||
|
||||
_ = try std.io.getStdIn().reader().readByte();
|
||||
}
|
||||
|
||||
@@ -1,64 +0,0 @@
|
||||
// File: binary_search.zig
|
||||
// Created Time: 2023-01-15
|
||||
// Author: codingonion (coderonion@gmail.com)
|
||||
|
||||
const std = @import("std");
|
||||
const inc = @import("include");
|
||||
|
||||
// 二分查找(双闭区间)
|
||||
fn binarySearch(comptime T: type, nums: std.ArrayList(T), target: T) T {
|
||||
// 初始化双闭区间 [0, n-1] ,即 i, j 分别指向数组首元素、尾元素
|
||||
var i: usize = 0;
|
||||
var j: usize = nums.items.len - 1;
|
||||
// 循环,当搜索区间为空时跳出(当 i > j 时为空)
|
||||
while (i <= j) {
|
||||
var m = i + (j - i) / 2; // 计算中点索引 m
|
||||
if (nums.items[m] < target) { // 此情况说明 target 在区间 [m+1, j] 中
|
||||
i = m + 1;
|
||||
} else if (nums.items[m] > target) { // 此情况说明 target 在区间 [i, m-1] 中
|
||||
j = m - 1;
|
||||
} else { // 找到目标元素,返回其索引
|
||||
return @intCast(m);
|
||||
}
|
||||
}
|
||||
// 未找到目标元素,返回 -1
|
||||
return -1;
|
||||
}
|
||||
|
||||
// 二分查找(左闭右开区间)
|
||||
fn binarySearchLCRO(comptime T: type, nums: std.ArrayList(T), target: T) T {
|
||||
// 初始化左闭右开区间 [0, n) ,即 i, j 分别指向数组首元素、尾元素+1
|
||||
var i: usize = 0;
|
||||
var j: usize = nums.items.len;
|
||||
// 循环,当搜索区间为空时跳出(当 i = j 时为空)
|
||||
while (i <= j) {
|
||||
var m = i + (j - i) / 2; // 计算中点索引 m
|
||||
if (nums.items[m] < target) { // 此情况说明 target 在区间 [m+1, j) 中
|
||||
i = m + 1;
|
||||
} else if (nums.items[m] > target) { // 此情况说明 target 在区间 [i, m) 中
|
||||
j = m;
|
||||
} else { // 找到目标元素,返回其索引
|
||||
return @intCast(m);
|
||||
}
|
||||
}
|
||||
// 未找到目标元素,返回 -1
|
||||
return -1;
|
||||
}
|
||||
|
||||
// Driver Code
|
||||
pub fn main() !void {
|
||||
var target: i32 = 6;
|
||||
var nums = std.ArrayList(i32).init(std.heap.page_allocator);
|
||||
defer nums.deinit();
|
||||
try nums.appendSlice(&[_]i32{ 1, 3, 6, 8, 12, 15, 23, 26, 31, 35 });
|
||||
|
||||
// 二分查找(双闭区间)
|
||||
var index = binarySearch(i32, nums, target);
|
||||
std.debug.print("目标元素 6 的索引 = {}\n", .{index});
|
||||
|
||||
// 二分查找(左闭右开区间)
|
||||
index = binarySearchLCRO(i32, nums, target);
|
||||
std.debug.print("目标元素 6 的索引 = {}\n", .{index});
|
||||
|
||||
_ = try std.io.getStdIn().reader().readByte();
|
||||
}
|
||||
@@ -1,57 +0,0 @@
|
||||
// File: hashing_search.zig
|
||||
// Created Time: 2023-01-15
|
||||
// Author: codingonion (coderonion@gmail.com)
|
||||
|
||||
const std = @import("std");
|
||||
const inc = @import("include");
|
||||
|
||||
// 哈希查找(数组)
|
||||
fn hashingSearchArray(comptime T: type, map: std.AutoHashMap(T, T), target: T) T {
|
||||
// 哈希表的 key: 目标元素,value: 索引
|
||||
// 若哈希表中无此 key ,返回 -1
|
||||
if (map.getKey(target) == null) return -1;
|
||||
return map.get(target).?;
|
||||
}
|
||||
|
||||
// 哈希查找(链表)
|
||||
fn hashingSearchLinkedList(comptime T: type, map: std.AutoHashMap(T, *inc.ListNode(T)), target: T) ?*inc.ListNode(T) {
|
||||
// 哈希表的 key: 目标节点值,value: 节点对象
|
||||
// 若哈希表中无此 key ,返回 null
|
||||
if (map.getKey(target) == null) return null;
|
||||
return map.get(target);
|
||||
}
|
||||
|
||||
// Driver Code
|
||||
pub fn main() !void {
|
||||
var target: i32 = 3;
|
||||
|
||||
// 哈希查找(数组)
|
||||
var nums = [_]i32{ 1, 5, 3, 2, 4, 7, 5, 9, 10, 8 };
|
||||
// 初始化哈希表
|
||||
var map = std.AutoHashMap(i32, i32).init(std.heap.page_allocator);
|
||||
defer map.deinit();
|
||||
for (nums, 0..) |num, i| {
|
||||
try map.put(num, @as(i32, @intCast(i))); // key: 元素,value: 索引
|
||||
}
|
||||
var index = hashingSearchArray(i32, map, target);
|
||||
std.debug.print("目标元素 3 的索引 = {}\n", .{index});
|
||||
|
||||
// 哈希查找(链表)
|
||||
var mem_arena = std.heap.ArenaAllocator.init(std.heap.page_allocator);
|
||||
defer mem_arena.deinit();
|
||||
const mem_allocator = mem_arena.allocator();
|
||||
var head = try inc.ListUtil.arrToLinkedList(i32, mem_allocator, &nums);
|
||||
// 初始化哈希表
|
||||
var map1 = std.AutoHashMap(i32, *inc.ListNode(i32)).init(std.heap.page_allocator);
|
||||
defer map1.deinit();
|
||||
while (head != null) {
|
||||
try map1.put(head.?.val, head.?);
|
||||
head = head.?.next;
|
||||
}
|
||||
var node = hashingSearchLinkedList(i32, map1, target);
|
||||
std.debug.print("目标节点值 3 的对应节点对象为 ", .{});
|
||||
try inc.PrintUtil.printLinkedList(i32, node);
|
||||
|
||||
_ = try std.io.getStdIn().reader().readByte();
|
||||
}
|
||||
|
||||
@@ -1,54 +0,0 @@
|
||||
// File: linear_search.zig
|
||||
// Created Time: 2023-01-13
|
||||
// Author: codingonion (coderonion@gmail.com)
|
||||
|
||||
const std = @import("std");
|
||||
const inc = @import("include");
|
||||
|
||||
// 线性查找(数组)
|
||||
fn linearSearchArray(comptime T: type, nums: std.ArrayList(T), target: T) T {
|
||||
// 遍历数组
|
||||
for (nums.items, 0..) |num, i| {
|
||||
// 找到目标元素, 返回其索引
|
||||
if (num == target) {
|
||||
return @intCast(i);
|
||||
}
|
||||
}
|
||||
// 未找到目标元素,返回 -1
|
||||
return -1;
|
||||
}
|
||||
|
||||
// 线性查找(链表)
|
||||
pub fn linearSearchLinkedList(comptime T: type, node: ?*inc.ListNode(T), target: T) ?*inc.ListNode(T) {
|
||||
var head = node;
|
||||
// 遍历链表
|
||||
while (head != null) {
|
||||
// 找到目标节点,返回之
|
||||
if (head.?.val == target) return head;
|
||||
head = head.?.next;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
// Driver Code
|
||||
pub fn main() !void {
|
||||
var target: i32 = 3;
|
||||
|
||||
// 在数组中执行线性查找
|
||||
var nums = std.ArrayList(i32).init(std.heap.page_allocator);
|
||||
defer nums.deinit();
|
||||
try nums.appendSlice(&[_]i32{ 1, 5, 3, 2, 4, 7, 5, 9, 10, 8 });
|
||||
var index = linearSearchArray(i32, nums, target);
|
||||
std.debug.print("目标元素 3 的索引 = {}\n", .{index});
|
||||
|
||||
// 在链表中执行线性查找
|
||||
var mem_arena = std.heap.ArenaAllocator.init(std.heap.page_allocator);
|
||||
defer mem_arena.deinit();
|
||||
const mem_allocator = mem_arena.allocator();
|
||||
var head = try inc.ListUtil.listToLinkedList(i32, mem_allocator, nums);
|
||||
var node = linearSearchLinkedList(i32, head, target);
|
||||
std.debug.print("目标节点值 3 的对应节点对象为 ", .{});
|
||||
try inc.PrintUtil.printLinkedList(i32, node);
|
||||
|
||||
_ = try std.io.getStdIn().reader().readByte();
|
||||
}
|
||||
@@ -1,58 +0,0 @@
|
||||
// File: two_sum.zig
|
||||
// Created Time: 2023-01-07
|
||||
// Author: codingonion (coderonion@gmail.com)
|
||||
|
||||
const std = @import("std");
|
||||
const inc = @import("include");
|
||||
|
||||
// 方法一:暴力枚举
|
||||
pub fn twoSumBruteForce(nums: []i32, target: i32) ?[2]i32 {
|
||||
var size: usize = nums.len;
|
||||
var i: usize = 0;
|
||||
// 两层循环,时间复杂度为 O(n^2)
|
||||
while (i < size - 1) : (i += 1) {
|
||||
var j = i + 1;
|
||||
while (j < size) : (j += 1) {
|
||||
if (nums[i] + nums[j] == target) {
|
||||
return [_]i32{@intCast(i), @intCast(j)};
|
||||
}
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
// 方法二:辅助哈希表
|
||||
pub fn twoSumHashTable(nums: []i32, target: i32) !?[2]i32 {
|
||||
var size: usize = nums.len;
|
||||
// 辅助哈希表,空间复杂度为 O(n)
|
||||
var dic = std.AutoHashMap(i32, i32).init(std.heap.page_allocator);
|
||||
defer dic.deinit();
|
||||
var i: usize = 0;
|
||||
// 单层循环,时间复杂度为 O(n)
|
||||
while (i < size) : (i += 1) {
|
||||
if (dic.contains(target - nums[i])) {
|
||||
return [_]i32{dic.get(target - nums[i]).?, @intCast(i)};
|
||||
}
|
||||
try dic.put(nums[i], @intCast(i));
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
|
||||
pub fn main() !void {
|
||||
// ======= Test Case =======
|
||||
var nums = [_]i32{ 2, 7, 11, 15 };
|
||||
var target: i32 = 9;
|
||||
|
||||
// ====== Driver Code ======
|
||||
// 方法一
|
||||
var res = twoSumBruteForce(&nums, target).?;
|
||||
std.debug.print("方法一 res = ", .{});
|
||||
inc.PrintUtil.printArray(i32, &res);
|
||||
// 方法二
|
||||
res = (try twoSumHashTable(&nums, target)).?;
|
||||
std.debug.print("\n方法二 res = ", .{});
|
||||
inc.PrintUtil.printArray(i32, &res);
|
||||
|
||||
_ = try std.io.getStdIn().reader().readByte();
|
||||
}
|
||||
@@ -1,61 +0,0 @@
|
||||
// File: bubble_sort.zig
|
||||
// Created Time: 2023-01-08
|
||||
// Author: codingonion (coderonion@gmail.com)
|
||||
|
||||
const std = @import("std");
|
||||
const inc = @import("include");
|
||||
|
||||
// 冒泡排序
|
||||
fn bubbleSort(nums: []i32) void {
|
||||
// 外循环:未排序区间为 [0, i]
|
||||
var i: usize = nums.len - 1;
|
||||
while (i > 0) : (i -= 1) {
|
||||
var j: usize = 0;
|
||||
// 内循环:将未排序区间 [0, i] 中的最大元素交换至该区间的最右端
|
||||
while (j < i) : (j += 1) {
|
||||
if (nums[j] > nums[j + 1]) {
|
||||
// 交换 nums[j] 与 nums[j + 1]
|
||||
var tmp = nums[j];
|
||||
nums[j] = nums[j + 1];
|
||||
nums[j + 1] = tmp;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// 冒泡排序(标志优化)
|
||||
fn bubbleSortWithFlag(nums: []i32) void {
|
||||
// 外循环:未排序区间为 [0, i]
|
||||
var i: usize = nums.len - 1;
|
||||
while (i > 0) : (i -= 1) {
|
||||
var flag = false; // 初始化标志位
|
||||
var j: usize = 0;
|
||||
// 内循环:将未排序区间 [0, i] 中的最大元素交换至该区间的最右端
|
||||
while (j < i) : (j += 1) {
|
||||
if (nums[j] > nums[j + 1]) {
|
||||
// 交换 nums[j] 与 nums[j + 1]
|
||||
var tmp = nums[j];
|
||||
nums[j] = nums[j + 1];
|
||||
nums[j + 1] = tmp;
|
||||
flag = true;
|
||||
}
|
||||
}
|
||||
if (!flag) break; // 此轮“冒泡”未交换任何元素,直接跳出
|
||||
}
|
||||
}
|
||||
|
||||
// Driver Code
|
||||
pub fn main() !void {
|
||||
var nums = [_]i32{ 4, 1, 3, 1, 5, 2 };
|
||||
bubbleSort(&nums);
|
||||
std.debug.print("冒泡排序完成后 nums = ", .{});
|
||||
inc.PrintUtil.printArray(i32, &nums);
|
||||
|
||||
var nums1 = [_]i32{ 4, 1, 3, 1, 5, 2 };
|
||||
bubbleSortWithFlag(&nums1);
|
||||
std.debug.print("\n冒泡排序完成后 nums1 = ", .{});
|
||||
inc.PrintUtil.printArray(i32, &nums1);
|
||||
|
||||
_ = try std.io.getStdIn().reader().readByte();
|
||||
}
|
||||
|
||||
@@ -1,31 +0,0 @@
|
||||
// File: insertion_sort.zig
|
||||
// Created Time: 2023-01-08
|
||||
// Author: codingonion (coderonion@gmail.com)
|
||||
|
||||
const std = @import("std");
|
||||
const inc = @import("include");
|
||||
|
||||
// 插入排序
|
||||
fn insertionSort(nums: []i32) void {
|
||||
// 外循环:已排序区间为 [0, i-1]
|
||||
var i: usize = 1;
|
||||
while (i < nums.len) : (i += 1) {
|
||||
var base = nums[i];
|
||||
var j: usize = i;
|
||||
// 内循环:将 base 插入到已排序区间 [0, i-1] 中的正确位置
|
||||
while (j >= 1 and nums[j - 1] > base) : (j -= 1) {
|
||||
nums[j] = nums[j - 1]; // 将 nums[j] 向右移动一位
|
||||
}
|
||||
nums[j] = base; // 将 base 赋值到正确位置
|
||||
}
|
||||
}
|
||||
|
||||
// Driver Code
|
||||
pub fn main() !void {
|
||||
var nums = [_]i32{ 4, 1, 3, 1, 5, 2 };
|
||||
insertionSort(&nums);
|
||||
std.debug.print("插入排序完成后 nums = ", .{});
|
||||
inc.PrintUtil.printArray(i32, &nums);
|
||||
|
||||
_ = try std.io.getStdIn().reader().readByte();
|
||||
}
|
||||
@@ -1,67 +0,0 @@
|
||||
// File: merge_sort.zig
|
||||
// Created Time: 2023-01-15
|
||||
// Author: codingonion (coderonion@gmail.com)
|
||||
|
||||
const std = @import("std");
|
||||
const inc = @import("include");
|
||||
|
||||
// 合并左子数组和右子数组
|
||||
// 左子数组区间 [left, mid]
|
||||
// 右子数组区间 [mid + 1, right]
|
||||
fn merge(nums: []i32, left: usize, mid: usize, right: usize) !void {
|
||||
// 初始化辅助数组
|
||||
var mem_arena = std.heap.ArenaAllocator.init(std.heap.page_allocator);
|
||||
defer mem_arena.deinit();
|
||||
const mem_allocator = mem_arena.allocator();
|
||||
var tmp = try mem_allocator.alloc(i32, right + 1 - left);
|
||||
std.mem.copy(i32, tmp, nums[left..right+1]);
|
||||
// 左子数组的起始索引和结束索引
|
||||
var leftStart = left - left;
|
||||
var leftEnd = mid - left;
|
||||
// 右子数组的起始索引和结束索引
|
||||
var rightStart = mid + 1 - left;
|
||||
var rightEnd = right - left;
|
||||
// i, j 分别指向左子数组、右子数组的首元素
|
||||
var i = leftStart;
|
||||
var j = rightStart;
|
||||
// 通过覆盖原数组 nums 来合并左子数组和右子数组
|
||||
var k = left;
|
||||
while (k <= right) : (k += 1) {
|
||||
// 若“左子数组已全部合并完”,则选取右子数组元素,并且 j++
|
||||
if (i > leftEnd) {
|
||||
nums[k] = tmp[j];
|
||||
j += 1;
|
||||
// 否则,若“右子数组已全部合并完”或“左子数组元素 <= 右子数组元素”,则选取左子数组元素,并且 i++
|
||||
} else if (j > rightEnd or tmp[i] <= tmp[j]) {
|
||||
nums[k] = tmp[i];
|
||||
i += 1;
|
||||
// 否则,若“左右子数组都未全部合并完”且“左子数组元素 > 右子数组元素”,则选取右子数组元素,并且 j++
|
||||
} else {
|
||||
nums[k] = tmp[j];
|
||||
j += 1;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// 归并排序
|
||||
fn mergeSort(nums: []i32, left: usize, right: usize) !void {
|
||||
// 终止条件
|
||||
if (left >= right) return; // 当子数组长度为 1 时终止递归
|
||||
// 划分阶段
|
||||
var mid = left + (right - left) / 2; // 计算中点
|
||||
try mergeSort(nums, left, mid); // 递归左子数组
|
||||
try mergeSort(nums, mid + 1, right); // 递归右子数组
|
||||
// 合并阶段
|
||||
try merge(nums, left, mid, right);
|
||||
}
|
||||
|
||||
// Driver Code
|
||||
pub fn main() !void {
|
||||
// 归并排序
|
||||
var nums = [_]i32{ 7, 3, 2, 6, 0, 1, 5, 4 };
|
||||
try mergeSort(&nums, 0, nums.len - 1);
|
||||
std.debug.print("归并排序完成后 nums = ", .{});
|
||||
inc.PrintUtil.printArray(i32, &nums);
|
||||
|
||||
_ = try std.io.getStdIn().reader().readByte();
|
||||
}
|
||||
@@ -1,162 +0,0 @@
|
||||
// File: quick_sort.zig
|
||||
// Created Time: 2023-01-15
|
||||
// Author: codingonion (coderonion@gmail.com)
|
||||
|
||||
const std = @import("std");
|
||||
const inc = @import("include");
|
||||
|
||||
// 快速排序类
|
||||
const QuickSort = struct {
|
||||
|
||||
// 元素交换
|
||||
pub fn swap(nums: []i32, i: usize, j: usize) void {
|
||||
var tmp = nums[i];
|
||||
nums[i] = nums[j];
|
||||
nums[j] = tmp;
|
||||
}
|
||||
|
||||
// 哨兵划分
|
||||
pub fn partition(nums: []i32, left: usize, right: usize) usize {
|
||||
// 以 nums[left] 为基准数
|
||||
var i = left;
|
||||
var j = right;
|
||||
while (i < j) {
|
||||
while (i < j and nums[j] >= nums[left]) j -= 1; // 从右向左找首个小于基准数的元素
|
||||
while (i < j and nums[i] <= nums[left]) i += 1; // 从左向右找首个大于基准数的元素
|
||||
swap(nums, i, j); // 交换这两个元素
|
||||
}
|
||||
swap(nums, i, left); // 将基准数交换至两子数组的分界线
|
||||
return i; // 返回基准数的索引
|
||||
}
|
||||
|
||||
// 快速排序
|
||||
pub fn quickSort(nums: []i32, left: usize, right: usize) void {
|
||||
// 子数组长度为 1 时终止递归
|
||||
if (left >= right) return;
|
||||
// 哨兵划分
|
||||
var pivot = partition(nums, left, right);
|
||||
// 递归左子数组、右子数组
|
||||
quickSort(nums, left, pivot - 1);
|
||||
quickSort(nums, pivot + 1, right);
|
||||
}
|
||||
};
|
||||
|
||||
// 快速排序类(中位基准数优化)
|
||||
const QuickSortMedian = struct {
|
||||
|
||||
// 元素交换
|
||||
pub fn swap(nums: []i32, i: usize, j: usize) void {
|
||||
var tmp = nums[i];
|
||||
nums[i] = nums[j];
|
||||
nums[j] = tmp;
|
||||
}
|
||||
|
||||
// 选取三个候选元素的中位数
|
||||
pub fn medianThree(nums: []i32, left: usize, mid: usize, right: usize) usize {
|
||||
var l = nums[left];
|
||||
var m = nums[mid];
|
||||
var r = nums[right];
|
||||
if ((l <= m && m <= r) || (r <= m && m <= l))
|
||||
return mid; // m 在 l 和 r 之间
|
||||
if ((m <= l && l <= r) || (r <= l && l <= m))
|
||||
return left; // l 在 m 和 r 之间
|
||||
return right;
|
||||
}
|
||||
|
||||
// 哨兵划分(三数取中值)
|
||||
pub fn partition(nums: []i32, left: usize, right: usize) usize {
|
||||
// 选取三个候选元素的中位数
|
||||
var med = medianThree(nums, left, (left + right) / 2, right);
|
||||
// 将中位数交换至数组最左端
|
||||
swap(nums, left, med);
|
||||
// 以 nums[left] 为基准数
|
||||
var i = left;
|
||||
var j = right;
|
||||
while (i < j) {
|
||||
while (i < j and nums[j] >= nums[left]) j -= 1; // 从右向左找首个小于基准数的元素
|
||||
while (i < j and nums[i] <= nums[left]) i += 1; // 从左向右找首个大于基准数的元素
|
||||
swap(nums, i, j); // 交换这两个元素
|
||||
}
|
||||
swap(nums, i, left); // 将基准数交换至两子数组的分界线
|
||||
return i; // 返回基准数的索引
|
||||
}
|
||||
|
||||
// 快速排序
|
||||
pub fn quickSort(nums: []i32, left: usize, right: usize) void {
|
||||
// 子数组长度为 1 时终止递归
|
||||
if (left >= right) return;
|
||||
// 哨兵划分
|
||||
var pivot = partition(nums, left, right);
|
||||
if (pivot == 0) return;
|
||||
// 递归左子数组、右子数组
|
||||
quickSort(nums, left, pivot - 1);
|
||||
quickSort(nums, pivot + 1, right);
|
||||
}
|
||||
};
|
||||
|
||||
// 快速排序类(递归深度优化)
|
||||
const QuickSortTailCall = struct {
|
||||
|
||||
// 元素交换
|
||||
pub fn swap(nums: []i32, i: usize, j: usize) void {
|
||||
var tmp = nums[i];
|
||||
nums[i] = nums[j];
|
||||
nums[j] = tmp;
|
||||
}
|
||||
|
||||
// 哨兵划分
|
||||
pub fn partition(nums: []i32, left: usize, right: usize) usize {
|
||||
// 以 nums[left] 为基准数
|
||||
var i = left;
|
||||
var j = right;
|
||||
while (i < j) {
|
||||
while (i < j and nums[j] >= nums[left]) j -= 1; // 从右向左找首个小于基准数的元素
|
||||
while (i < j and nums[i] <= nums[left]) i += 1; // 从左向右找首个大于基准数的元素
|
||||
swap(nums, i, j); // 交换这两个元素
|
||||
}
|
||||
swap(nums, i, left); // 将基准数交换至两子数组的分界线
|
||||
return i; // 返回基准数的索引
|
||||
}
|
||||
|
||||
// 快速排序(递归深度优化)
|
||||
pub fn quickSort(nums: []i32, left_: usize, right_: usize) void {
|
||||
var left = left_;
|
||||
var right = right_;
|
||||
// 子数组长度为 1 时终止递归
|
||||
while (left < right) {
|
||||
// 哨兵划分操作
|
||||
var pivot = partition(nums, left, right);
|
||||
// 对两个子数组中较短的那个执行快速排序
|
||||
if (pivot - left < right - pivot) {
|
||||
quickSort(nums, left, pivot - 1); // 递归排序左子数组
|
||||
left = pivot + 1; // 剩余未排序区间为 [pivot + 1, right]
|
||||
} else {
|
||||
quickSort(nums, pivot + 1, right); // 递归排序右子数组
|
||||
right = pivot - 1; // 剩余未排序区间为 [left, pivot - 1]
|
||||
}
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
// Driver Code
|
||||
pub fn main() !void {
|
||||
// 快速排序
|
||||
var nums = [_]i32{ 2, 4, 1, 0, 3, 5 };
|
||||
QuickSort.quickSort(&nums, 0, nums.len - 1);
|
||||
std.debug.print("快速排序完成后 nums = ", .{});
|
||||
inc.PrintUtil.printArray(i32, &nums);
|
||||
|
||||
// 快速排序(中位基准数优化)
|
||||
var nums1 = [_]i32{ 2, 4, 1, 0, 3, 5 };
|
||||
QuickSortMedian.quickSort(&nums1, 0, nums1.len - 1);
|
||||
std.debug.print("\n快速排序(中位基准数优化)完成后 nums = ", .{});
|
||||
inc.PrintUtil.printArray(i32, &nums1);
|
||||
|
||||
// 快速排序(递归深度优化)
|
||||
var nums2 = [_]i32{ 2, 4, 1, 0, 3, 5 };
|
||||
QuickSortTailCall.quickSort(&nums2, 0, nums2.len - 1);
|
||||
std.debug.print("\n快速排序(递归深度优化)完成后 nums = ", .{});
|
||||
inc.PrintUtil.printArray(i32, &nums2);
|
||||
|
||||
_ = try std.io.getStdIn().reader().readByte();
|
||||
}
|
||||
@@ -1,77 +0,0 @@
|
||||
// File: radix_sort.zig
|
||||
// Created Time: 2023-01-15
|
||||
// Author: codingonion (coderonion@gmail.com)
|
||||
|
||||
const std = @import("std");
|
||||
const inc = @import("include");
|
||||
|
||||
// 获取元素 num 的第 k 位,其中 exp = 10^(k-1)
|
||||
fn digit(num: i32, exp: i32) i32 {
|
||||
// 传入 exp 而非 k 可以避免在此重复执行昂贵的次方计算
|
||||
return @mod(@divFloor(num, exp), 10);
|
||||
}
|
||||
|
||||
// 计数排序(根据 nums 第 k 位排序)
|
||||
fn countingSortDigit(nums: []i32, exp: i32) !void {
|
||||
// 十进制的位范围为 0~9 ,因此需要长度为 10 的桶数组
|
||||
var mem_arena = std.heap.ArenaAllocator.init(std.heap.page_allocator);
|
||||
// defer mem_arena.deinit();
|
||||
const mem_allocator = mem_arena.allocator();
|
||||
var counter = try mem_allocator.alloc(usize, 10);
|
||||
@memset(counter, 0);
|
||||
var n = nums.len;
|
||||
// 统计 0~9 各数字的出现次数
|
||||
for (nums) |num| {
|
||||
var d: u32 = @bitCast(digit(num, exp)); // 获取 nums[i] 第 k 位,记为 d
|
||||
counter[d] += 1; // 统计数字 d 的出现次数
|
||||
}
|
||||
// 求前缀和,将“出现个数”转换为“数组索引”
|
||||
var i: usize = 1;
|
||||
while (i < 10) : (i += 1) {
|
||||
counter[i] += counter[i - 1];
|
||||
}
|
||||
// 倒序遍历,根据桶内统计结果,将各元素填入 res
|
||||
var res = try mem_allocator.alloc(i32, n);
|
||||
i = n - 1;
|
||||
while (i >= 0) : (i -= 1) {
|
||||
var d: u32 = @bitCast(digit(nums[i], exp));
|
||||
var j = counter[d] - 1; // 获取 d 在数组中的索引 j
|
||||
res[j] = nums[i]; // 将当前元素填入索引 j
|
||||
counter[d] -= 1; // 将 d 的数量减 1
|
||||
if (i == 0) break;
|
||||
}
|
||||
// 使用结果覆盖原数组 nums
|
||||
i = 0;
|
||||
while (i < n) : (i += 1) {
|
||||
nums[i] = res[i];
|
||||
}
|
||||
}
|
||||
|
||||
// 基数排序
|
||||
fn radixSort(nums: []i32) !void {
|
||||
// 获取数组的最大元素,用于判断最大位数
|
||||
var m: i32 = std.math.minInt(i32);
|
||||
for (nums) |num| {
|
||||
if (num > m) m = num;
|
||||
}
|
||||
// 按照从低位到高位的顺序遍历
|
||||
var exp: i32 = 1;
|
||||
while (exp <= m) : (exp *= 10) {
|
||||
// 对数组元素的第 k 位执行计数排序
|
||||
// k = 1 -> exp = 1
|
||||
// k = 2 -> exp = 10
|
||||
// 即 exp = 10^(k-1)
|
||||
try countingSortDigit(nums, exp);
|
||||
}
|
||||
}
|
||||
|
||||
// Driver Code
|
||||
pub fn main() !void {
|
||||
// 基数排序
|
||||
var nums = [_]i32{ 23, 12, 3, 4, 788, 192 };
|
||||
try radixSort(&nums);
|
||||
std.debug.print("基数排序完成后 nums = ", .{});
|
||||
inc.PrintUtil.printArray(i32, &nums);
|
||||
|
||||
_ = try std.io.getStdIn().reader().readByte();
|
||||
}
|
||||
@@ -1,140 +0,0 @@
|
||||
// File: array_queue.zig
|
||||
// Created Time: 2023-01-15
|
||||
// Author: codingonion (coderonion@gmail.com)
|
||||
|
||||
const std = @import("std");
|
||||
const inc = @import("include");
|
||||
|
||||
// 基于环形数组实现的队列
|
||||
pub fn ArrayQueue(comptime T: type) type {
|
||||
return struct {
|
||||
const Self = @This();
|
||||
|
||||
nums: []T = undefined, // 用于存储队列元素的数组
|
||||
cap: usize = 0, // 队列容量
|
||||
front: usize = 0, // 队首指针,指向队首元素
|
||||
queSize: usize = 0, // 尾指针,指向队尾 + 1
|
||||
mem_arena: ?std.heap.ArenaAllocator = null,
|
||||
mem_allocator: std.mem.Allocator = undefined, // 内存分配器
|
||||
|
||||
// 构造函数(分配内存+初始化数组)
|
||||
pub fn init(self: *Self, allocator: std.mem.Allocator, cap: usize) !void {
|
||||
if (self.mem_arena == null) {
|
||||
self.mem_arena = std.heap.ArenaAllocator.init(allocator);
|
||||
self.mem_allocator = self.mem_arena.?.allocator();
|
||||
}
|
||||
self.cap = cap;
|
||||
self.nums = try self.mem_allocator.alloc(T, self.cap);
|
||||
@memset(self.nums, @as(T, 0));
|
||||
}
|
||||
|
||||
// 析构函数(释放内存)
|
||||
pub fn deinit(self: *Self) void {
|
||||
if (self.mem_arena == null) return;
|
||||
self.mem_arena.?.deinit();
|
||||
}
|
||||
|
||||
// 获取队列的容量
|
||||
pub fn capacity(self: *Self) usize {
|
||||
return self.cap;
|
||||
}
|
||||
|
||||
// 获取队列的长度
|
||||
pub fn size(self: *Self) usize {
|
||||
return self.queSize;
|
||||
}
|
||||
|
||||
// 判断队列是否为空
|
||||
pub fn isEmpty(self: *Self) bool {
|
||||
return self.queSize == 0;
|
||||
}
|
||||
|
||||
// 入队
|
||||
pub fn push(self: *Self, num: T) !void {
|
||||
if (self.size() == self.capacity()) {
|
||||
std.debug.print("队列已满\n", .{});
|
||||
return;
|
||||
}
|
||||
// 计算队尾指针,指向队尾索引 + 1
|
||||
// 通过取余操作实现 rear 越过数组尾部后回到头部
|
||||
var rear = (self.front + self.queSize) % self.capacity();
|
||||
// 在尾节点后添加 num
|
||||
self.nums[rear] = num;
|
||||
self.queSize += 1;
|
||||
}
|
||||
|
||||
// 出队
|
||||
pub fn pop(self: *Self) T {
|
||||
var num = self.peek();
|
||||
// 队首指针向后移动一位,若越过尾部,则返回到数组头部
|
||||
self.front = (self.front + 1) % self.capacity();
|
||||
self.queSize -= 1;
|
||||
return num;
|
||||
}
|
||||
|
||||
// 访问队首元素
|
||||
pub fn peek(self: *Self) T {
|
||||
if (self.isEmpty()) @panic("队列为空");
|
||||
return self.nums[self.front];
|
||||
}
|
||||
|
||||
// 返回数组
|
||||
pub fn toArray(self: *Self) ![]T {
|
||||
// 仅转换有效长度范围内的列表元素
|
||||
var res = try self.mem_allocator.alloc(T, self.size());
|
||||
@memset(res, @as(T, 0));
|
||||
var i: usize = 0;
|
||||
var j: usize = self.front;
|
||||
while (i < self.size()) : ({ i += 1; j += 1; }) {
|
||||
res[i] = self.nums[j % self.capacity()];
|
||||
}
|
||||
return res;
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
// Driver Code
|
||||
pub fn main() !void {
|
||||
// 初始化队列
|
||||
var capacity: usize = 10;
|
||||
var queue = ArrayQueue(i32){};
|
||||
try queue.init(std.heap.page_allocator, capacity);
|
||||
defer queue.deinit();
|
||||
|
||||
// 元素入队
|
||||
try queue.push(1);
|
||||
try queue.push(3);
|
||||
try queue.push(2);
|
||||
try queue.push(5);
|
||||
try queue.push(4);
|
||||
std.debug.print("队列 queue = ", .{});
|
||||
inc.PrintUtil.printArray(i32, try queue.toArray());
|
||||
|
||||
// 访问队首元素
|
||||
var peek = queue.peek();
|
||||
std.debug.print("\n队首元素 peek = {}", .{peek});
|
||||
|
||||
// 元素出队
|
||||
var pop = queue.pop();
|
||||
std.debug.print("\n出队元素 pop = {},出队后 queue = ", .{pop});
|
||||
inc.PrintUtil.printArray(i32, try queue.toArray());
|
||||
|
||||
// 获取队列的长度
|
||||
var size = queue.size();
|
||||
std.debug.print("\n队列长度 size = {}", .{size});
|
||||
|
||||
// 判断队列是否为空
|
||||
var is_empty = queue.isEmpty();
|
||||
std.debug.print("\n队列是否为空 = {}", .{is_empty});
|
||||
|
||||
// 测试环形数组
|
||||
var i: i32 = 0;
|
||||
while (i < 10) : (i += 1) {
|
||||
try queue.push(i);
|
||||
_ = queue.pop();
|
||||
std.debug.print("\n第 {} 轮入队 + 出队后 queue = ", .{i});
|
||||
inc.PrintUtil.printArray(i32, try queue.toArray());
|
||||
}
|
||||
|
||||
_ = try std.io.getStdIn().reader().readByte();
|
||||
}
|
||||
@@ -1,97 +0,0 @@
|
||||
// File: array_stack.zig
|
||||
// Created Time: 2023-01-08
|
||||
// Author: codingonion (coderonion@gmail.com)
|
||||
|
||||
const std = @import("std");
|
||||
const inc = @import("include");
|
||||
|
||||
// 基于数组实现的栈
|
||||
pub fn ArrayStack(comptime T: type) type {
|
||||
return struct {
|
||||
const Self = @This();
|
||||
|
||||
stack: ?std.ArrayList(T) = null,
|
||||
|
||||
// 构造方法(分配内存+初始化栈)
|
||||
pub fn init(self: *Self, allocator: std.mem.Allocator) void {
|
||||
if (self.stack == null) {
|
||||
self.stack = std.ArrayList(T).init(allocator);
|
||||
}
|
||||
}
|
||||
|
||||
// 析构方法(释放内存)
|
||||
pub fn deinit(self: *Self) void {
|
||||
if (self.stack == null) return;
|
||||
self.stack.?.deinit();
|
||||
}
|
||||
|
||||
// 获取栈的长度
|
||||
pub fn size(self: *Self) usize {
|
||||
return self.stack.?.items.len;
|
||||
}
|
||||
|
||||
// 判断栈是否为空
|
||||
pub fn isEmpty(self: *Self) bool {
|
||||
return self.size() == 0;
|
||||
}
|
||||
|
||||
// 访问栈顶元素
|
||||
pub fn peek(self: *Self) T {
|
||||
if (self.isEmpty()) @panic("栈为空");
|
||||
return self.stack.?.items[self.size() - 1];
|
||||
}
|
||||
|
||||
// 入栈
|
||||
pub fn push(self: *Self, num: T) !void {
|
||||
try self.stack.?.append(num);
|
||||
}
|
||||
|
||||
// 出栈
|
||||
pub fn pop(self: *Self) T {
|
||||
var num = self.stack.?.pop();
|
||||
return num;
|
||||
}
|
||||
|
||||
// 返回 ArrayList
|
||||
pub fn toList(self: *Self) std.ArrayList(T) {
|
||||
return self.stack.?;
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
// Driver Code
|
||||
pub fn main() !void {
|
||||
// 初始化栈
|
||||
var stack = ArrayStack(i32){};
|
||||
stack.init(std.heap.page_allocator);
|
||||
// 延迟释放内存
|
||||
defer stack.deinit();
|
||||
|
||||
// 元素入栈
|
||||
try stack.push(1);
|
||||
try stack.push(3);
|
||||
try stack.push(2);
|
||||
try stack.push(5);
|
||||
try stack.push(4);
|
||||
std.debug.print("栈 stack = ", .{});
|
||||
inc.PrintUtil.printList(i32, stack.toList());
|
||||
|
||||
// 访问栈顶元素
|
||||
var peek = stack.peek();
|
||||
std.debug.print("\n栈顶元素 peek = {}", .{peek});
|
||||
|
||||
// 元素出栈
|
||||
var top = stack.pop();
|
||||
std.debug.print("\n出栈元素 pop = {},出栈后 stack = ", .{top});
|
||||
inc.PrintUtil.printList(i32, stack.toList());
|
||||
|
||||
// 获取栈的长度
|
||||
var size = stack.size();
|
||||
std.debug.print("\n栈的长度 size = {}", .{size});
|
||||
|
||||
// 判断栈是否为空
|
||||
var is_empty = stack.isEmpty();
|
||||
std.debug.print("\n栈是否为空 = {}", .{is_empty});
|
||||
|
||||
_ = try std.io.getStdIn().reader().readByte();
|
||||
}
|
||||
@@ -1,51 +0,0 @@
|
||||
// File: deque.zig
|
||||
// Created Time: 2023-01-15
|
||||
// Author: codingonion (coderonion@gmail.com)
|
||||
|
||||
const std = @import("std");
|
||||
const inc = @import("include");
|
||||
|
||||
// Driver Code
|
||||
pub fn main() !void {
|
||||
// 初始化双向队列
|
||||
const L = std.TailQueue(i32);
|
||||
var deque = L{};
|
||||
|
||||
// 元素入队
|
||||
var node1 = L.Node{ .data = 2 };
|
||||
var node2 = L.Node{ .data = 5 };
|
||||
var node3 = L.Node{ .data = 4 };
|
||||
var node4 = L.Node{ .data = 3 };
|
||||
var node5 = L.Node{ .data = 1 };
|
||||
deque.append(&node1); // 添加至队尾
|
||||
deque.append(&node2);
|
||||
deque.append(&node3);
|
||||
deque.prepend(&node4); // 添加至队首
|
||||
deque.prepend(&node5);
|
||||
std.debug.print("双向队列 deque = ", .{});
|
||||
inc.PrintUtil.printQueue(i32, deque);
|
||||
|
||||
// 访问元素
|
||||
var peek_first = deque.first.?.data; // 队首元素
|
||||
std.debug.print("\n队首元素 peek_first = {}", .{peek_first});
|
||||
var peek_last = deque.last.?.data; // 队尾元素
|
||||
std.debug.print("\n队尾元素 peek_last = {}", .{peek_last});
|
||||
|
||||
// 元素出队
|
||||
var pop_first = deque.popFirst().?.data; // 队首元素出队
|
||||
std.debug.print("\n队首出队元素 pop_first = {},队首出队后 deque = ", .{pop_first});
|
||||
inc.PrintUtil.printQueue(i32, deque);
|
||||
var pop_last = deque.pop().?.data; // 队尾元素出队
|
||||
std.debug.print("\n队尾出队元素 pop_last = {},队尾出队后 deque = ", .{pop_last});
|
||||
inc.PrintUtil.printQueue(i32, deque);
|
||||
|
||||
// 获取双向队列的长度
|
||||
var size = deque.len;
|
||||
std.debug.print("\n双向队列长度 size = {}", .{size});
|
||||
|
||||
// 判断双向队列是否为空
|
||||
var is_empty = if (deque.len == 0) true else false;
|
||||
std.debug.print("\n双向队列是否为空 = {}", .{is_empty});
|
||||
|
||||
_ = try std.io.getStdIn().reader().readByte();
|
||||
}
|
||||
@@ -1,209 +0,0 @@
|
||||
// File: linkedlist_deque.zig
|
||||
// Created Time: 2023-01-15
|
||||
// Author: codingonion (coderonion@gmail.com)
|
||||
|
||||
const std = @import("std");
|
||||
const inc = @import("include");
|
||||
|
||||
// 双向链表节点
|
||||
pub fn ListNode(comptime T: type) type {
|
||||
return struct {
|
||||
const Self = @This();
|
||||
|
||||
val: T = undefined, // 节点值
|
||||
next: ?*Self = null, // 后继节点指针
|
||||
prev: ?*Self = null, // 前驱节点指针
|
||||
|
||||
// Initialize a list node with specific value
|
||||
pub fn init(self: *Self, x: i32) void {
|
||||
self.val = x;
|
||||
self.next = null;
|
||||
self.prev = null;
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
// 基于双向链表实现的双向队列
|
||||
pub fn LinkedListDeque(comptime T: type) type {
|
||||
return struct {
|
||||
const Self = @This();
|
||||
|
||||
front: ?*ListNode(T) = null, // 头节点 front
|
||||
rear: ?*ListNode(T) = null, // 尾节点 rear
|
||||
que_size: usize = 0, // 双向队列的长度
|
||||
mem_arena: ?std.heap.ArenaAllocator = null,
|
||||
mem_allocator: std.mem.Allocator = undefined, // 内存分配器
|
||||
|
||||
// 构造函数(分配内存+初始化队列)
|
||||
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.front = null;
|
||||
self.rear = null;
|
||||
self.que_size = 0;
|
||||
}
|
||||
|
||||
// 析构函数(释放内存)
|
||||
pub fn deinit(self: *Self) void {
|
||||
if (self.mem_arena == null) return;
|
||||
self.mem_arena.?.deinit();
|
||||
}
|
||||
|
||||
// 获取双向队列的长度
|
||||
pub fn size(self: *Self) usize {
|
||||
return self.que_size;
|
||||
}
|
||||
|
||||
// 判断双向队列是否为空
|
||||
pub fn isEmpty(self: *Self) bool {
|
||||
return self.size() == 0;
|
||||
}
|
||||
|
||||
// 入队操作
|
||||
pub fn push(self: *Self, num: T, is_front: bool) !void {
|
||||
var node = try self.mem_allocator.create(ListNode(T));
|
||||
node.init(num);
|
||||
// 若链表为空,则令 front 和 rear 都指向 node
|
||||
if (self.isEmpty()) {
|
||||
self.front = node;
|
||||
self.rear = node;
|
||||
// 队首入队操作
|
||||
} else if (is_front) {
|
||||
// 将 node 添加至链表头部
|
||||
self.front.?.prev = node;
|
||||
node.next = self.front;
|
||||
self.front = node; // 更新头节点
|
||||
// 队尾入队操作
|
||||
} else {
|
||||
// 将 node 添加至链表尾部
|
||||
self.rear.?.next = node;
|
||||
node.prev = self.rear;
|
||||
self.rear = node; // 更新尾节点
|
||||
}
|
||||
self.que_size += 1; // 更新队列长度
|
||||
}
|
||||
|
||||
// 队首入队
|
||||
pub fn pushFirst(self: *Self, num: T) !void {
|
||||
try self.push(num, true);
|
||||
}
|
||||
|
||||
// 队尾入队
|
||||
pub fn pushLast(self: *Self, num: T) !void {
|
||||
try self.push(num, false);
|
||||
}
|
||||
|
||||
// 出队操作
|
||||
pub fn pop(self: *Self, is_front: bool) T {
|
||||
if (self.isEmpty()) @panic("双向队列为空");
|
||||
var val: T = undefined;
|
||||
// 队列长度为 1 时, 头尾指向同一节点
|
||||
if (self.que_size == 1) {
|
||||
val = self.front.?.val;
|
||||
self.front = null;
|
||||
self.rear = null;
|
||||
}
|
||||
// 队首出队操作
|
||||
else if (is_front) {
|
||||
val = self.front.?.val; // 暂存头节点值
|
||||
// 删除头节点
|
||||
var fNext = self.front.?.next;
|
||||
fNext.?.prev = null;
|
||||
self.front.?.next = null;
|
||||
self.front = fNext; // 更新头节点
|
||||
// 队尾出队操作
|
||||
} else {
|
||||
val = self.rear.?.val; // 暂存尾节点值
|
||||
// 删除尾节点
|
||||
var rPrev = self.rear.?.prev;
|
||||
rPrev.?.next = null;
|
||||
self.rear.?.prev = null;
|
||||
self.rear = rPrev; // 更新尾节点
|
||||
}
|
||||
self.que_size -= 1; // 更新队列长度
|
||||
return val;
|
||||
}
|
||||
|
||||
// 队首出队
|
||||
pub fn popFirst(self: *Self) T {
|
||||
return self.pop(true);
|
||||
}
|
||||
|
||||
// 队尾出队
|
||||
pub fn popLast(self: *Self) T {
|
||||
return self.pop(false);
|
||||
}
|
||||
|
||||
// 访问队首元素
|
||||
pub fn peekFirst(self: *Self) T {
|
||||
if (self.isEmpty()) @panic("双向队列为空");
|
||||
return self.front.?.val;
|
||||
}
|
||||
|
||||
// 访问队尾元素
|
||||
pub fn peekLast(self: *Self) T {
|
||||
if (self.isEmpty()) @panic("双向队列为空");
|
||||
return self.rear.?.val;
|
||||
}
|
||||
|
||||
// 返回数组用于打印
|
||||
pub fn toArray(self: *Self) ![]T {
|
||||
var node = self.front;
|
||||
var res = try self.mem_allocator.alloc(T, self.size());
|
||||
@memset(res, @as(T, 0));
|
||||
var i: usize = 0;
|
||||
while (i < res.len) : (i += 1) {
|
||||
res[i] = node.?.val;
|
||||
node = node.?.next;
|
||||
}
|
||||
return res;
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
// Driver Code
|
||||
pub fn main() !void {
|
||||
// 初始化双向队列
|
||||
var deque = LinkedListDeque(i32){};
|
||||
try deque.init(std.heap.page_allocator);
|
||||
defer deque.deinit();
|
||||
try deque.pushLast(3);
|
||||
try deque.pushLast(2);
|
||||
try deque.pushLast(5);
|
||||
std.debug.print("双向队列 deque = ", .{});
|
||||
inc.PrintUtil.printArray(i32, try deque.toArray());
|
||||
|
||||
// 访问元素
|
||||
var peek_first = deque.peekFirst();
|
||||
std.debug.print("\n队首元素 peek_first = {}", .{peek_first});
|
||||
var peek_last = deque.peekLast();
|
||||
std.debug.print("\n队尾元素 peek_last = {}", .{peek_last});
|
||||
|
||||
// 元素入队
|
||||
try deque.pushLast(4);
|
||||
std.debug.print("\n元素 4 队尾入队后 deque = ", .{});
|
||||
inc.PrintUtil.printArray(i32, try deque.toArray());
|
||||
try deque.pushFirst(1);
|
||||
std.debug.print("\n元素 1 队首入队后 deque = ", .{});
|
||||
inc.PrintUtil.printArray(i32, try deque.toArray());
|
||||
|
||||
// 元素出队
|
||||
var pop_last = deque.popLast();
|
||||
std.debug.print("\n队尾出队元素 = {},队尾出队后 deque = ", .{pop_last});
|
||||
inc.PrintUtil.printArray(i32, try deque.toArray());
|
||||
var pop_first = deque.popFirst();
|
||||
std.debug.print("\n队首出队元素 = {},队首出队后 deque = ", .{pop_first});
|
||||
inc.PrintUtil.printArray(i32, try deque.toArray());
|
||||
|
||||
// 获取双向队列的长度
|
||||
var size = deque.size();
|
||||
std.debug.print("\n双向队列长度 size = {}", .{size});
|
||||
|
||||
// 判断双向队列是否为空
|
||||
var is_empty = deque.isEmpty();
|
||||
std.debug.print("\n双向队列是否为空 = {}", .{is_empty});
|
||||
|
||||
_ = try std.io.getStdIn().reader().readByte();
|
||||
}
|
||||
@@ -1,127 +0,0 @@
|
||||
// File: linkedlist_queue.zig
|
||||
// Created Time: 2023-01-15
|
||||
// Author: codingonion (coderonion@gmail.com)
|
||||
|
||||
const std = @import("std");
|
||||
const inc = @import("include");
|
||||
|
||||
// 基于链表实现的队列
|
||||
pub fn LinkedListQueue(comptime T: type) type {
|
||||
return struct {
|
||||
const Self = @This();
|
||||
|
||||
front: ?*inc.ListNode(T) = null, // 头节点 front
|
||||
rear: ?*inc.ListNode(T) = null, // 尾节点 rear
|
||||
que_size: usize = 0, // 队列的长度
|
||||
mem_arena: ?std.heap.ArenaAllocator = null,
|
||||
mem_allocator: std.mem.Allocator = undefined, // 内存分配器
|
||||
|
||||
// 构造函数(分配内存+初始化队列)
|
||||
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.front = null;
|
||||
self.rear = null;
|
||||
self.que_size = 0;
|
||||
}
|
||||
|
||||
// 析构函数(释放内存)
|
||||
pub fn deinit(self: *Self) void {
|
||||
if (self.mem_arena == null) return;
|
||||
self.mem_arena.?.deinit();
|
||||
}
|
||||
|
||||
// 获取队列的长度
|
||||
pub fn size(self: *Self) usize {
|
||||
return self.que_size;
|
||||
}
|
||||
|
||||
// 判断队列是否为空
|
||||
pub fn isEmpty(self: *Self) bool {
|
||||
return self.size() == 0;
|
||||
}
|
||||
|
||||
// 访问队首元素
|
||||
pub fn peek(self: *Self) T {
|
||||
if (self.size() == 0) @panic("队列为空");
|
||||
return self.front.?.val;
|
||||
}
|
||||
|
||||
// 入队
|
||||
pub fn push(self: *Self, num: T) !void {
|
||||
// 在尾节点后添加 num
|
||||
var node = try self.mem_allocator.create(inc.ListNode(T));
|
||||
node.init(num);
|
||||
// 如果队列为空,则令头、尾节点都指向该节点
|
||||
if (self.front == null) {
|
||||
self.front = node;
|
||||
self.rear = node;
|
||||
// 如果队列不为空,则将该节点添加到尾节点后
|
||||
} else {
|
||||
self.rear.?.next = node;
|
||||
self.rear = node;
|
||||
}
|
||||
self.que_size += 1;
|
||||
}
|
||||
|
||||
// 出队
|
||||
pub fn pop(self: *Self) T {
|
||||
var num = self.peek();
|
||||
// 删除头节点
|
||||
self.front = self.front.?.next;
|
||||
self.que_size -= 1;
|
||||
return num;
|
||||
}
|
||||
|
||||
// 将链表转换为数组
|
||||
pub fn toArray(self: *Self) ![]T {
|
||||
var node = self.front;
|
||||
var res = try self.mem_allocator.alloc(T, self.size());
|
||||
@memset(res, @as(T, 0));
|
||||
var i: usize = 0;
|
||||
while (i < res.len) : (i += 1) {
|
||||
res[i] = node.?.val;
|
||||
node = node.?.next;
|
||||
}
|
||||
return res;
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
// Driver Code
|
||||
pub fn main() !void {
|
||||
// 初始化队列
|
||||
var queue = LinkedListQueue(i32){};
|
||||
try queue.init(std.heap.page_allocator);
|
||||
defer queue.deinit();
|
||||
|
||||
// 元素入队
|
||||
try queue.push(1);
|
||||
try queue.push(3);
|
||||
try queue.push(2);
|
||||
try queue.push(5);
|
||||
try queue.push(4);
|
||||
std.debug.print("队列 queue = ", .{});
|
||||
inc.PrintUtil.printArray(i32, try queue.toArray());
|
||||
|
||||
// 访问队首元素
|
||||
var peek = queue.peek();
|
||||
std.debug.print("\n队首元素 peek = {}", .{peek});
|
||||
|
||||
// 元素出队
|
||||
var pop = queue.pop();
|
||||
std.debug.print("\n出队元素 pop = {},出队后 queue = ", .{pop});
|
||||
inc.PrintUtil.printArray(i32, try queue.toArray());
|
||||
|
||||
// 获取队列的长度
|
||||
var size = queue.size();
|
||||
std.debug.print("\n队列长度 size = {}", .{size});
|
||||
|
||||
// 判断队列是否为空
|
||||
var is_empty = queue.isEmpty();
|
||||
std.debug.print("\n队列是否为空 = {}", .{is_empty});
|
||||
|
||||
_ = try std.io.getStdIn().reader().readByte();
|
||||
}
|
||||
@@ -1,118 +0,0 @@
|
||||
// File: linkedlist_stack.zig
|
||||
// Created Time: 2023-01-08
|
||||
// Author: codingonion (coderonion@gmail.com)
|
||||
|
||||
const std = @import("std");
|
||||
const inc = @import("include");
|
||||
|
||||
// 基于链表实现的栈
|
||||
pub fn LinkedListStack(comptime T: type) type {
|
||||
return struct {
|
||||
const Self = @This();
|
||||
|
||||
stack_top: ?*inc.ListNode(T) = null, // 将头节点作为栈顶
|
||||
stk_size: usize = 0, // 栈的长度
|
||||
mem_arena: ?std.heap.ArenaAllocator = null,
|
||||
mem_allocator: std.mem.Allocator = undefined, // 内存分配器
|
||||
|
||||
// 构造函数(分配内存+初始化栈)
|
||||
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.stack_top = null;
|
||||
self.stk_size = 0;
|
||||
}
|
||||
|
||||
// 析构函数(释放内存)
|
||||
pub fn deinit(self: *Self) void {
|
||||
if (self.mem_arena == null) return;
|
||||
self.mem_arena.?.deinit();
|
||||
}
|
||||
|
||||
// 获取栈的长度
|
||||
pub fn size(self: *Self) usize {
|
||||
return self.stk_size;
|
||||
}
|
||||
|
||||
// 判断栈是否为空
|
||||
pub fn isEmpty(self: *Self) bool {
|
||||
return self.size() == 0;
|
||||
}
|
||||
|
||||
// 访问栈顶元素
|
||||
pub fn peek(self: *Self) T {
|
||||
if (self.size() == 0) @panic("栈为空");
|
||||
return self.stack_top.?.val;
|
||||
}
|
||||
|
||||
// 入栈
|
||||
pub fn push(self: *Self, num: T) !void {
|
||||
var node = try self.mem_allocator.create(inc.ListNode(T));
|
||||
node.init(num);
|
||||
node.next = self.stack_top;
|
||||
self.stack_top = node;
|
||||
self.stk_size += 1;
|
||||
}
|
||||
|
||||
// 出栈
|
||||
pub fn pop(self: *Self) T {
|
||||
var num = self.peek();
|
||||
self.stack_top = self.stack_top.?.next;
|
||||
self.stk_size -= 1;
|
||||
return num;
|
||||
}
|
||||
|
||||
// 将栈转换为数组
|
||||
pub fn toArray(self: *Self) ![]T {
|
||||
var node = self.stack_top;
|
||||
var res = try self.mem_allocator.alloc(T, self.size());
|
||||
@memset(res, @as(T, 0));
|
||||
var i: usize = 0;
|
||||
while (i < res.len) : (i += 1) {
|
||||
res[res.len - i - 1] = node.?.val;
|
||||
node = node.?.next;
|
||||
}
|
||||
return res;
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
// Driver Code
|
||||
pub fn main() !void {
|
||||
// 初始化栈
|
||||
var stack = LinkedListStack(i32){};
|
||||
try stack.init(std.heap.page_allocator);
|
||||
// 延迟释放内存
|
||||
defer stack.deinit();
|
||||
|
||||
// 元素入栈
|
||||
try stack.push(1);
|
||||
try stack.push(3);
|
||||
try stack.push(2);
|
||||
try stack.push(5);
|
||||
try stack.push(4);
|
||||
std.debug.print("栈 stack = ", .{});
|
||||
inc.PrintUtil.printArray(i32, try stack.toArray());
|
||||
|
||||
// 访问栈顶元素
|
||||
var peek = stack.peek();
|
||||
std.debug.print("\n栈顶元素 top = {}", .{peek});
|
||||
|
||||
// 元素出栈
|
||||
var pop = stack.pop();
|
||||
std.debug.print("\n出栈元素 pop = {},出栈后 stack = ", .{pop});
|
||||
inc.PrintUtil.printArray(i32, try stack.toArray());
|
||||
|
||||
// 获取栈的长度
|
||||
var size = stack.size();
|
||||
std.debug.print("\n栈的长度 size = {}", .{size});
|
||||
|
||||
// 判断栈是否为空
|
||||
var is_empty = stack.isEmpty();
|
||||
std.debug.print("\n栈是否为空 = {}", .{is_empty});
|
||||
|
||||
_ = try std.io.getStdIn().reader().readByte();
|
||||
}
|
||||
|
||||
@@ -1,46 +0,0 @@
|
||||
// File: queue.zig
|
||||
// Created Time: 2023-01-15
|
||||
// Author: codingonion (coderonion@gmail.com)
|
||||
|
||||
const std = @import("std");
|
||||
const inc = @import("include");
|
||||
|
||||
// Driver Code
|
||||
pub fn main() !void {
|
||||
// 初始化队列
|
||||
const L = std.TailQueue(i32);
|
||||
var queue = L{};
|
||||
|
||||
// 元素入队
|
||||
var node1 = L.Node{ .data = 1 };
|
||||
var node2 = L.Node{ .data = 3 };
|
||||
var node3 = L.Node{ .data = 2 };
|
||||
var node4 = L.Node{ .data = 5 };
|
||||
var node5 = L.Node{ .data = 4 };
|
||||
queue.append(&node1);
|
||||
queue.append(&node2);
|
||||
queue.append(&node3);
|
||||
queue.append(&node4);
|
||||
queue.append(&node5);
|
||||
std.debug.print("队列 queue = ", .{});
|
||||
inc.PrintUtil.printQueue(i32, queue);
|
||||
|
||||
// 访问队首元素
|
||||
var peek = queue.first.?.data;
|
||||
std.debug.print("\n队首元素 peek = {}", .{peek});
|
||||
|
||||
// 元素出队
|
||||
var pop = queue.popFirst().?.data;
|
||||
std.debug.print("\n出队元素 pop = {},出队后 queue = ", .{pop});
|
||||
inc.PrintUtil.printQueue(i32, queue);
|
||||
|
||||
// 获取队列的长度
|
||||
var size = queue.len;
|
||||
std.debug.print("\n队列长度 size = {}", .{size});
|
||||
|
||||
// 判断队列是否为空
|
||||
var is_empty = if (queue.len == 0) true else false;
|
||||
std.debug.print("\n队列是否为空 = {}", .{is_empty});
|
||||
|
||||
_ = try std.io.getStdIn().reader().readByte();
|
||||
}
|
||||
@@ -1,43 +0,0 @@
|
||||
// File: stack.zig
|
||||
// Created Time: 2023-01-08
|
||||
// Author: codingonion (coderonion@gmail.com)
|
||||
|
||||
const std = @import("std");
|
||||
const inc = @import("include");
|
||||
|
||||
// Driver Code
|
||||
pub fn main() !void {
|
||||
// 初始化栈
|
||||
// 在 zig 中,推荐将 ArrayList 当作栈来使用
|
||||
var stack = std.ArrayList(i32).init(std.heap.page_allocator);
|
||||
// 延迟释放内存
|
||||
defer stack.deinit();
|
||||
|
||||
// 元素入栈
|
||||
try stack.append(1);
|
||||
try stack.append(3);
|
||||
try stack.append(2);
|
||||
try stack.append(5);
|
||||
try stack.append(4);
|
||||
std.debug.print("栈 stack = ", .{});
|
||||
inc.PrintUtil.printList(i32, stack);
|
||||
|
||||
// 访问栈顶元素
|
||||
var peek = stack.items[stack.items.len - 1];
|
||||
std.debug.print("\n栈顶元素 peek = {}", .{peek});
|
||||
|
||||
// 元素出栈
|
||||
var pop = stack.pop();
|
||||
std.debug.print("\n出栈元素 pop = {},出栈后 stack = ", .{pop});
|
||||
inc.PrintUtil.printList(i32, stack);
|
||||
|
||||
// 获取栈的长度
|
||||
var size = stack.items.len;
|
||||
std.debug.print("\n栈的长度 size = {}", .{size});
|
||||
|
||||
// 判断栈是否为空
|
||||
var is_empty = if (stack.items.len == 0) true else false;
|
||||
std.debug.print("\n栈是否为空 = {}", .{is_empty});
|
||||
|
||||
_ = try std.io.getStdIn().reader().readByte();
|
||||
}
|
||||
@@ -1,249 +0,0 @@
|
||||
// File: avl_tree.zig
|
||||
// Created Time: 2023-01-15
|
||||
// Author: codingonion (coderonion@gmail.com)
|
||||
|
||||
const std = @import("std");
|
||||
const inc = @import("include");
|
||||
|
||||
// AVL 树
|
||||
pub fn AVLTree(comptime T: type) type {
|
||||
return struct {
|
||||
const Self = @This();
|
||||
|
||||
root: ?*inc.TreeNode(T) = null, // 根节点
|
||||
mem_arena: ?std.heap.ArenaAllocator = null,
|
||||
mem_allocator: std.mem.Allocator = undefined, // 内存分配器
|
||||
|
||||
// 构造方法
|
||||
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();
|
||||
}
|
||||
}
|
||||
|
||||
// 析构方法
|
||||
pub fn deinit(self: *Self) void {
|
||||
if (self.mem_arena == null) return;
|
||||
self.mem_arena.?.deinit();
|
||||
}
|
||||
|
||||
// 获取节点高度
|
||||
fn height(self: *Self, node: ?*inc.TreeNode(T)) i32 {
|
||||
_ = self;
|
||||
// 空节点高度为 -1 ,叶节点高度为 0
|
||||
return if (node == null) -1 else node.?.height;
|
||||
}
|
||||
|
||||
// 更新节点高度
|
||||
fn updateHeight(self: *Self, node: ?*inc.TreeNode(T)) void {
|
||||
// 节点高度等于最高子树高度 + 1
|
||||
node.?.height = @max(self.height(node.?.left), self.height(node.?.right)) + 1;
|
||||
}
|
||||
|
||||
// 获取平衡因子
|
||||
fn balanceFactor(self: *Self, node: ?*inc.TreeNode(T)) i32 {
|
||||
// 空节点平衡因子为 0
|
||||
if (node == null) return 0;
|
||||
// 节点平衡因子 = 左子树高度 - 右子树高度
|
||||
return self.height(node.?.left) - self.height(node.?.right);
|
||||
}
|
||||
|
||||
// 右旋操作
|
||||
fn rightRotate(self: *Self, node: ?*inc.TreeNode(T)) ?*inc.TreeNode(T) {
|
||||
var child = node.?.left;
|
||||
var grandChild = child.?.right;
|
||||
// 以 child 为原点,将 node 向右旋转
|
||||
child.?.right = node;
|
||||
node.?.left = grandChild;
|
||||
// 更新节点高度
|
||||
self.updateHeight(node);
|
||||
self.updateHeight(child);
|
||||
// 返回旋转后子树的根节点
|
||||
return child;
|
||||
}
|
||||
|
||||
// 左旋操作
|
||||
fn leftRotate(self: *Self, node: ?*inc.TreeNode(T)) ?*inc.TreeNode(T) {
|
||||
var child = node.?.right;
|
||||
var grandChild = child.?.left;
|
||||
// 以 child 为原点,将 node 向左旋转
|
||||
child.?.left = node;
|
||||
node.?.right = grandChild;
|
||||
// 更新节点高度
|
||||
self.updateHeight(node);
|
||||
self.updateHeight(child);
|
||||
// 返回旋转后子树的根节点
|
||||
return child;
|
||||
}
|
||||
|
||||
// 执行旋转操作,使该子树重新恢复平衡
|
||||
fn rotate(self: *Self, node: ?*inc.TreeNode(T)) ?*inc.TreeNode(T) {
|
||||
// 获取节点 node 的平衡因子
|
||||
var balance_factor = self.balanceFactor(node);
|
||||
// 左偏树
|
||||
if (balance_factor > 1) {
|
||||
if (self.balanceFactor(node.?.left) >= 0) {
|
||||
// 右旋
|
||||
return self.rightRotate(node);
|
||||
} else {
|
||||
// 先左旋后右旋
|
||||
node.?.left = self.leftRotate(node.?.left);
|
||||
return self.rightRotate(node);
|
||||
}
|
||||
}
|
||||
// 右偏树
|
||||
if (balance_factor < -1) {
|
||||
if (self.balanceFactor(node.?.right) <= 0) {
|
||||
// 左旋
|
||||
return self.leftRotate(node);
|
||||
} else {
|
||||
// 先右旋后左旋
|
||||
node.?.right = self.rightRotate(node.?.right);
|
||||
return self.leftRotate(node);
|
||||
}
|
||||
}
|
||||
// 平衡树,无须旋转,直接返回
|
||||
return node;
|
||||
}
|
||||
|
||||
// 插入节点
|
||||
fn insert(self: *Self, val: T) !void {
|
||||
self.root = (try self.insertHelper(self.root, val)).?;
|
||||
}
|
||||
|
||||
// 递归插入节点(辅助方法)
|
||||
fn insertHelper(self: *Self, node_: ?*inc.TreeNode(T), val: T) !?*inc.TreeNode(T) {
|
||||
var node = node_;
|
||||
if (node == null) {
|
||||
var tmp_node = try self.mem_allocator.create(inc.TreeNode(T));
|
||||
tmp_node.init(val);
|
||||
return tmp_node;
|
||||
}
|
||||
// 1. 查找插入位置并插入节点
|
||||
if (val < node.?.val) {
|
||||
node.?.left = try self.insertHelper(node.?.left, val);
|
||||
} else if (val > node.?.val) {
|
||||
node.?.right = try self.insertHelper(node.?.right, val);
|
||||
} else {
|
||||
return node; // 重复节点不插入,直接返回
|
||||
}
|
||||
self.updateHeight(node); // 更新节点高度
|
||||
// 2. 执行旋转操作,使该子树重新恢复平衡
|
||||
node = self.rotate(node);
|
||||
// 返回子树的根节点
|
||||
return node;
|
||||
}
|
||||
|
||||
// 删除节点
|
||||
fn remove(self: *Self, val: T) void {
|
||||
self.root = self.removeHelper(self.root, val).?;
|
||||
}
|
||||
|
||||
// 递归删除节点(辅助方法)
|
||||
fn removeHelper(self: *Self, node_: ?*inc.TreeNode(T), val: T) ?*inc.TreeNode(T) {
|
||||
var node = node_;
|
||||
if (node == null) return null;
|
||||
// 1. 查找节点并删除
|
||||
if (val < node.?.val) {
|
||||
node.?.left = self.removeHelper(node.?.left, val);
|
||||
} else if (val > node.?.val) {
|
||||
node.?.right = self.removeHelper(node.?.right, val);
|
||||
} else {
|
||||
if (node.?.left == null or node.?.right == null) {
|
||||
var child = if (node.?.left != null) node.?.left else node.?.right;
|
||||
// 子节点数量 = 0 ,直接删除 node 并返回
|
||||
if (child == null) {
|
||||
return null;
|
||||
// 子节点数量 = 1 ,直接删除 node
|
||||
} else {
|
||||
node = child;
|
||||
}
|
||||
} else {
|
||||
// 子节点数量 = 2 ,则将中序遍历的下个节点删除,并用该节点替换当前节点
|
||||
var temp = node.?.right;
|
||||
while (temp.?.left != null) {
|
||||
temp = temp.?.left;
|
||||
}
|
||||
node.?.right = self.removeHelper(node.?.right, temp.?.val);
|
||||
node.?.val = temp.?.val;
|
||||
}
|
||||
}
|
||||
self.updateHeight(node); // 更新节点高度
|
||||
// 2. 执行旋转操作,使该子树重新恢复平衡
|
||||
node = self.rotate(node);
|
||||
// 返回子树的根节点
|
||||
return node;
|
||||
}
|
||||
|
||||
// 查找节点
|
||||
fn search(self: *Self, val: T) ?*inc.TreeNode(T) {
|
||||
var cur = self.root;
|
||||
// 循环查找,越过叶节点后跳出
|
||||
while (cur != null) {
|
||||
// 目标节点在 cur 的右子树中
|
||||
if (cur.?.val < val) {
|
||||
cur = cur.?.right;
|
||||
// 目标节点在 cur 的左子树中
|
||||
} else if (cur.?.val > val) {
|
||||
cur = cur.?.left;
|
||||
// 找到目标节点,跳出循环
|
||||
} else {
|
||||
break;
|
||||
}
|
||||
}
|
||||
// 返回目标节点
|
||||
return cur;
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
pub fn testInsert(comptime T: type, tree_: *AVLTree(T), val: T) !void {
|
||||
var tree = tree_;
|
||||
try tree.insert(val);
|
||||
std.debug.print("\n插入节点 {} 后,AVL 树为\n", .{val});
|
||||
try inc.PrintUtil.printTree(tree.root, null, false);
|
||||
}
|
||||
|
||||
pub fn testRemove(comptime T: type, tree_: *AVLTree(T), val: T) void {
|
||||
var tree = tree_;
|
||||
tree.remove(val);
|
||||
std.debug.print("\n删除节点 {} 后,AVL 树为\n", .{val});
|
||||
try inc.PrintUtil.printTree(tree.root, null, false);
|
||||
}
|
||||
|
||||
// Driver Code
|
||||
pub fn main() !void {
|
||||
// 初始化空 AVL 树
|
||||
var avl_tree = AVLTree(i32){};
|
||||
avl_tree.init(std.heap.page_allocator);
|
||||
defer avl_tree.deinit();
|
||||
|
||||
// 插入节点
|
||||
// 请关注插入节点后,AVL 树是如何保持平衡的
|
||||
try testInsert(i32, &avl_tree, 1);
|
||||
try testInsert(i32, &avl_tree, 2);
|
||||
try testInsert(i32, &avl_tree, 3);
|
||||
try testInsert(i32, &avl_tree, 4);
|
||||
try testInsert(i32, &avl_tree, 5);
|
||||
try testInsert(i32, &avl_tree, 8);
|
||||
try testInsert(i32, &avl_tree, 7);
|
||||
try testInsert(i32, &avl_tree, 9);
|
||||
try testInsert(i32, &avl_tree, 10);
|
||||
try testInsert(i32, &avl_tree, 6);
|
||||
|
||||
// 插入重复节点
|
||||
try testInsert(i32, &avl_tree, 7);
|
||||
|
||||
// 删除节点
|
||||
// 请关注删除节点后,AVL 树是如何保持平衡的
|
||||
testRemove(i32, &avl_tree, 8); // 删除度为 0 的节点
|
||||
testRemove(i32, &avl_tree, 5); // 删除度为 1 的节点
|
||||
testRemove(i32, &avl_tree, 4); // 删除度为 2 的节点
|
||||
|
||||
// 查找节点
|
||||
var node = avl_tree.search(7).?;
|
||||
std.debug.print("\n查找到的节点对象为 {any},节点值 = {}\n", .{node, node.val});
|
||||
|
||||
_ = try std.io.getStdIn().reader().readByte();
|
||||
}
|
||||
@@ -1,182 +0,0 @@
|
||||
// File: binary_search_tree.zig
|
||||
// Created Time: 2023-01-15
|
||||
// Author: codingonion (coderonion@gmail.com)
|
||||
|
||||
const std = @import("std");
|
||||
const inc = @import("include");
|
||||
|
||||
// 二叉搜索树
|
||||
pub fn BinarySearchTree(comptime T: type) type {
|
||||
return struct {
|
||||
const Self = @This();
|
||||
|
||||
root: ?*inc.TreeNode(T) = null,
|
||||
mem_arena: ?std.heap.ArenaAllocator = null,
|
||||
mem_allocator: std.mem.Allocator = undefined, // 内存分配器
|
||||
|
||||
// 构造方法
|
||||
pub fn init(self: *Self, allocator: std.mem.Allocator, nums: []T) !void {
|
||||
if (self.mem_arena == null) {
|
||||
self.mem_arena = std.heap.ArenaAllocator.init(allocator);
|
||||
self.mem_allocator = self.mem_arena.?.allocator();
|
||||
}
|
||||
std.mem.sort(T, nums, {}, comptime std.sort.asc(T)); // 排序数组
|
||||
self.root = try self.buildTree(nums, 0, nums.len - 1); // 构建二叉搜索树
|
||||
}
|
||||
|
||||
// 析构方法
|
||||
pub fn deinit(self: *Self) void {
|
||||
if (self.mem_arena == null) return;
|
||||
self.mem_arena.?.deinit();
|
||||
}
|
||||
|
||||
// 构建二叉搜索树
|
||||
fn buildTree(self: *Self, nums: []T, i: usize, j: usize) !?*inc.TreeNode(T) {
|
||||
if (i > j) return null;
|
||||
// 将数组中间节点作为根节点
|
||||
var mid = i + (j - i) / 2;
|
||||
var node = try self.mem_allocator.create(inc.TreeNode(T));
|
||||
node.init(nums[mid]);
|
||||
// 递归建立左子树和右子树
|
||||
if (mid >= 1) node.left = try self.buildTree(nums, i, mid - 1);
|
||||
node.right = try self.buildTree(nums, mid + 1, j);
|
||||
return node;
|
||||
}
|
||||
|
||||
// 获取二叉树根节点
|
||||
fn getRoot(self: *Self) ?*inc.TreeNode(T) {
|
||||
return self.root;
|
||||
}
|
||||
|
||||
// 查找节点
|
||||
fn search(self: *Self, num: T) ?*inc.TreeNode(T) {
|
||||
var cur = self.root;
|
||||
// 循环查找,越过叶节点后跳出
|
||||
while (cur != null) {
|
||||
// 目标节点在 cur 的右子树中
|
||||
if (cur.?.val < num) {
|
||||
cur = cur.?.right;
|
||||
// 目标节点在 cur 的左子树中
|
||||
} else if (cur.?.val > num) {
|
||||
cur = cur.?.left;
|
||||
// 找到目标节点,跳出循环
|
||||
} else {
|
||||
break;
|
||||
}
|
||||
}
|
||||
// 返回目标节点
|
||||
return cur;
|
||||
}
|
||||
|
||||
// 插入节点
|
||||
fn insert(self: *Self, num: T) !void {
|
||||
// 若树为空,则初始化根节点
|
||||
if (self.root == null) {
|
||||
self.root = try self.mem_allocator.create(inc.TreeNode(T));
|
||||
return;
|
||||
}
|
||||
var cur = self.root;
|
||||
var pre: ?*inc.TreeNode(T) = null;
|
||||
// 循环查找,越过叶节点后跳出
|
||||
while (cur != null) {
|
||||
// 找到重复节点,直接返回
|
||||
if (cur.?.val == num) return;
|
||||
pre = cur;
|
||||
// 插入位置在 cur 的右子树中
|
||||
if (cur.?.val < num) {
|
||||
cur = cur.?.right;
|
||||
// 插入位置在 cur 的左子树中
|
||||
} else {
|
||||
cur = cur.?.left;
|
||||
}
|
||||
}
|
||||
// 插入节点
|
||||
var node = try self.mem_allocator.create(inc.TreeNode(T));
|
||||
node.init(num);
|
||||
if (pre.?.val < num) {
|
||||
pre.?.right = node;
|
||||
} else {
|
||||
pre.?.left = node;
|
||||
}
|
||||
}
|
||||
|
||||
// 删除节点
|
||||
fn remove(self: *Self, num: T) void {
|
||||
// 若树为空,直接提前返回
|
||||
if (self.root == null) return;
|
||||
var cur = self.root;
|
||||
var pre: ?*inc.TreeNode(T) = null;
|
||||
// 循环查找,越过叶节点后跳出
|
||||
while (cur != null) {
|
||||
// 找到待删除节点,跳出循环
|
||||
if (cur.?.val == num) break;
|
||||
pre = cur;
|
||||
// 待删除节点在 cur 的右子树中
|
||||
if (cur.?.val < num) {
|
||||
cur = cur.?.right;
|
||||
// 待删除节点在 cur 的左子树中
|
||||
} else {
|
||||
cur = cur.?.left;
|
||||
}
|
||||
}
|
||||
// 若无待删除节点,则直接返回
|
||||
if (cur == null) return;
|
||||
// 子节点数量 = 0 or 1
|
||||
if (cur.?.left == null or cur.?.right == null) {
|
||||
// 当子节点数量 = 0 / 1 时, child = null / 该子节点
|
||||
var child = if (cur.?.left != null) cur.?.left else cur.?.right;
|
||||
// 删除节点 cur
|
||||
if (pre.?.left == cur) {
|
||||
pre.?.left = child;
|
||||
} else {
|
||||
pre.?.right = child;
|
||||
}
|
||||
// 子节点数量 = 2
|
||||
} else {
|
||||
// 获取中序遍历中 cur 的下一个节点
|
||||
var tmp = cur.?.right;
|
||||
while (tmp.?.left != null) {
|
||||
tmp = tmp.?.left;
|
||||
}
|
||||
var tmp_val = tmp.?.val;
|
||||
// 递归删除节点 tmp
|
||||
self.remove(tmp.?.val);
|
||||
// 用 tmp 覆盖 cur
|
||||
cur.?.val = tmp_val;
|
||||
}
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
// Driver Code
|
||||
pub fn main() !void {
|
||||
// 初始化二叉树
|
||||
var nums = [_]i32{ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15 };
|
||||
var bst = BinarySearchTree(i32){};
|
||||
try bst.init(std.heap.page_allocator, &nums);
|
||||
defer bst.deinit();
|
||||
std.debug.print("初始化的二叉树为\n", .{});
|
||||
try inc.PrintUtil.printTree(bst.getRoot(), null, false);
|
||||
|
||||
// 查找节点
|
||||
var node = bst.search(7);
|
||||
std.debug.print("\n查找到的节点对象为 {any},节点值 = {}\n", .{node, node.?.val});
|
||||
|
||||
// 插入节点
|
||||
try bst.insert(16);
|
||||
std.debug.print("\n插入节点 16 后,二叉树为\n", .{});
|
||||
try inc.PrintUtil.printTree(bst.getRoot(), null, false);
|
||||
|
||||
// 删除节点
|
||||
bst.remove(1);
|
||||
std.debug.print("\n删除节点 1 后,二叉树为\n", .{});
|
||||
try inc.PrintUtil.printTree(bst.getRoot(), null, false);
|
||||
bst.remove(2);
|
||||
std.debug.print("\n删除节点 2 后,二叉树为\n", .{});
|
||||
try inc.PrintUtil.printTree(bst.getRoot(), null, false);
|
||||
bst.remove(4);
|
||||
std.debug.print("\n删除节点 4 后,二叉树为\n", .{});
|
||||
try inc.PrintUtil.printTree(bst.getRoot(), null, false);
|
||||
|
||||
_ = try std.io.getStdIn().reader().readByte();
|
||||
}
|
||||
@@ -1,39 +0,0 @@
|
||||
// File: binary_tree.zig
|
||||
// Created Time: 2023-01-14
|
||||
// Author: codingonion (coderonion@gmail.com)
|
||||
|
||||
const std = @import("std");
|
||||
const inc = @import("include");
|
||||
|
||||
// Driver Code
|
||||
pub fn main() !void {
|
||||
// 初始化二叉树
|
||||
// 初始化节点
|
||||
var n1 = inc.TreeNode(i32){ .val = 1 };
|
||||
var n2 = inc.TreeNode(i32){ .val = 2 };
|
||||
var n3 = inc.TreeNode(i32){ .val = 3 };
|
||||
var n4 = inc.TreeNode(i32){ .val = 4 };
|
||||
var n5 = inc.TreeNode(i32){ .val = 5 };
|
||||
// 构建节点之间的引用(指针)
|
||||
n1.left = &n2;
|
||||
n1.right = &n3;
|
||||
n2.left = &n4;
|
||||
n2.right = &n5;
|
||||
std.debug.print("初始化二叉树\n", .{});
|
||||
try inc.PrintUtil.printTree(&n1, null, false);
|
||||
|
||||
// 插入与删除节点
|
||||
var p = inc.TreeNode(i32){ .val = 0 };
|
||||
// 在 n1 -> n2 中间插入节点 P
|
||||
n1.left = &p;
|
||||
p.left = &n2;
|
||||
std.debug.print("插入节点 P 后\n", .{});
|
||||
try inc.PrintUtil.printTree(&n1, null, false);
|
||||
// 删除节点
|
||||
n1.left = &n2;
|
||||
std.debug.print("删除节点 P 后\n", .{});
|
||||
try inc.PrintUtil.printTree(&n1, null, false);
|
||||
|
||||
_ = try std.io.getStdIn().reader().readByte();
|
||||
}
|
||||
|
||||
@@ -1,57 +0,0 @@
|
||||
// File: binary_tree_bfs.zig
|
||||
// Created Time: 2023-01-15
|
||||
// Author: codingonion (coderonion@gmail.com)
|
||||
|
||||
const std = @import("std");
|
||||
const inc = @import("include");
|
||||
|
||||
// 层序遍历
|
||||
fn levelOrder(comptime T: type, mem_allocator: std.mem.Allocator, root: *inc.TreeNode(T)) !std.ArrayList(T) {
|
||||
// 初始化队列,加入根节点
|
||||
const L = std.TailQueue(*inc.TreeNode(T));
|
||||
var queue = L{};
|
||||
var root_node = try mem_allocator.create(L.Node);
|
||||
root_node.data = root;
|
||||
queue.append(root_node);
|
||||
// 初始化一个列表,用于保存遍历序列
|
||||
var list = std.ArrayList(T).init(std.heap.page_allocator);
|
||||
while (queue.len > 0) {
|
||||
var queue_node = queue.popFirst().?; // 队列出队
|
||||
var node = queue_node.data;
|
||||
try list.append(node.val); // 保存节点值
|
||||
if (node.left != null) {
|
||||
var tmp_node = try mem_allocator.create(L.Node);
|
||||
tmp_node.data = node.left.?;
|
||||
queue.append(tmp_node); // 左子节点入队
|
||||
}
|
||||
if (node.right != null) {
|
||||
var tmp_node = try mem_allocator.create(L.Node);
|
||||
tmp_node.data = node.right.?;
|
||||
queue.append(tmp_node); // 右子节点入队
|
||||
}
|
||||
}
|
||||
return list;
|
||||
}
|
||||
|
||||
// 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();
|
||||
|
||||
// 初始化二叉树
|
||||
// 这里借助了一个从数组直接生成二叉树的函数
|
||||
var nums = [_]i32{1, 2, 3, 4, 5, 6, 7};
|
||||
var root = try inc.TreeUtil.arrToTree(i32, mem_allocator, &nums);
|
||||
std.debug.print("初始化二叉树\n", .{});
|
||||
try inc.PrintUtil.printTree(root, null, false);
|
||||
|
||||
// 层序遍历
|
||||
var list = try levelOrder(i32, mem_allocator, root.?);
|
||||
defer list.deinit();
|
||||
std.debug.print("\n层序遍历的节点打印序列 = ", .{});
|
||||
inc.PrintUtil.printList(i32, list);
|
||||
|
||||
_ = try std.io.getStdIn().reader().readByte();
|
||||
}
|
||||
@@ -1,70 +0,0 @@
|
||||
// File: binary_tree_dfs.zig
|
||||
// Created Time: 2023-01-15
|
||||
// Author: codingonion (coderonion@gmail.com)
|
||||
|
||||
const std = @import("std");
|
||||
const inc = @import("include");
|
||||
|
||||
var list = std.ArrayList(i32).init(std.heap.page_allocator);
|
||||
|
||||
// 前序遍历
|
||||
fn preOrder(comptime T: type, root: ?*inc.TreeNode(T)) !void {
|
||||
if (root == null) return;
|
||||
// 访问优先级:根节点 -> 左子树 -> 右子树
|
||||
try list.append(root.?.val);
|
||||
try preOrder(T, root.?.left);
|
||||
try preOrder(T, root.?.right);
|
||||
}
|
||||
|
||||
// 中序遍历
|
||||
fn inOrder(comptime T: type, root: ?*inc.TreeNode(T)) !void {
|
||||
if (root == null) return;
|
||||
// 访问优先级:左子树 -> 根节点 -> 右子树
|
||||
try inOrder(T, root.?.left);
|
||||
try list.append(root.?.val);
|
||||
try inOrder(T, root.?.right);
|
||||
}
|
||||
|
||||
// 后序遍历
|
||||
fn postOrder(comptime T: type, root: ?*inc.TreeNode(T)) !void {
|
||||
if (root == null) return;
|
||||
// 访问优先级:左子树 -> 右子树 -> 根节点
|
||||
try postOrder(T, root.?.left);
|
||||
try postOrder(T, root.?.right);
|
||||
try list.append(root.?.val);
|
||||
}
|
||||
|
||||
// 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();
|
||||
|
||||
// 初始化二叉树
|
||||
// 这里借助了一个从数组直接生成二叉树的函数
|
||||
var nums = [_]i32{1, 2, 3, 4, 5, 6, 7};
|
||||
var root = try inc.TreeUtil.arrToTree(i32, mem_allocator, &nums);
|
||||
std.debug.print("初始化二叉树\n", .{});
|
||||
try inc.PrintUtil.printTree(root, null, false);
|
||||
|
||||
// 前序遍历
|
||||
list.clearRetainingCapacity();
|
||||
try preOrder(i32, root);
|
||||
std.debug.print("\n前序遍历的节点打印序列 = ", .{});
|
||||
inc.PrintUtil.printList(i32, list);
|
||||
|
||||
// 中序遍历
|
||||
list.clearRetainingCapacity();
|
||||
try inOrder(i32, root);
|
||||
std.debug.print("\n中序遍历的节点打印序列 = ", .{});
|
||||
inc.PrintUtil.printList(i32, list);
|
||||
|
||||
// 后序遍历
|
||||
list.clearRetainingCapacity();
|
||||
try postOrder(i32, root);
|
||||
std.debug.print("\n后续遍历的节点打印序列 = ", .{});
|
||||
inc.PrintUtil.printList(i32, list);
|
||||
|
||||
_ = try std.io.getStdIn().reader().readByte();
|
||||
}
|
||||
@@ -1,42 +0,0 @@
|
||||
// File: PrintUtil.zig
|
||||
// Created Time: 2023-01-07
|
||||
// Author: codingonion (coderonion@gmail.com)
|
||||
|
||||
const std = @import("std");
|
||||
pub const ListUtil = @import("ListNode.zig");
|
||||
pub const ListNode = ListUtil.ListNode;
|
||||
pub const TreeUtil = @import("TreeNode.zig");
|
||||
pub const TreeNode = TreeUtil.TreeNode;
|
||||
|
||||
// 打印队列
|
||||
pub fn printQueue(comptime T: type, queue: std.TailQueue(T)) void {
|
||||
var node = queue.first;
|
||||
std.debug.print("[", .{});
|
||||
var i: i32 = 0;
|
||||
while (node != null) : (i += 1) {
|
||||
var data = node.?.data;
|
||||
std.debug.print("{}{s}", .{ data, if (i == queue.len - 1) "]" else ", " });
|
||||
node = node.?.next;
|
||||
}
|
||||
}
|
||||
|
||||
// 打印哈希表
|
||||
pub fn printHashMap(comptime TKey: type, comptime TValue: type, map: std.AutoHashMap(TKey, TValue)) void {
|
||||
var it = map.iterator();
|
||||
while (it.next()) |kv| {
|
||||
var key = kv.key_ptr.*;
|
||||
var value = kv.value_ptr.*;
|
||||
std.debug.print("{} -> {s}\n", .{ key, value });
|
||||
}
|
||||
}
|
||||
|
||||
// 打印堆
|
||||
pub fn printHeap(comptime T: type, mem_allocator: std.mem.Allocator, queue: anytype) !void {
|
||||
var arr = queue.items;
|
||||
var len = queue.len;
|
||||
std.debug.print("堆的数组表示:", .{});
|
||||
printArray(T, arr[0..len]);
|
||||
std.debug.print("\n堆的树状表示:\n", .{});
|
||||
var root = try TreeUtil.arrToTree(T, mem_allocator, arr[0..len]);
|
||||
try printTree(root, null, false);
|
||||
}
|
||||
@@ -1,7 +0,0 @@
|
||||
// File: include.zig
|
||||
// Created Time: 2023-01-07
|
||||
// Author: codingonion (coderonion@gmail.com)
|
||||
|
||||
pub const PrintUtil = @import("PrintUtil.zig");
|
||||
pub const TreeUtil = @import("TreeNode.zig");
|
||||
pub const TreeNode = TreeUtil.TreeNode;
|
||||
@@ -25,7 +25,7 @@ RUN for LANG in $LANGS; do \
|
||||
apt-get install -y dotnet-sdk-8.0 ;; \
|
||||
# More languages...
|
||||
*) \
|
||||
echo "Warning: No installation workflow for $LANG" ;; \
|
||||
echo "Error: No installation workflow for $LANG" >&2; exit 1 ;; \
|
||||
esac \
|
||||
done
|
||||
|
||||
|
||||
@@ -16,13 +16,6 @@ pub fn build(b: *std.Build) void {
|
||||
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",
|
||||
};
|
||||
|
||||
const test_step = b.step("test", "Run unit tests");
|
||||
@@ -41,14 +34,13 @@ fn buildChapterExeModules(
|
||||
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;
|
||||
var chapter_dir = std.fs.cwd().openDir(chapter_dir_name, .{ .iterate = true }) catch |err| @panic(@errorName(err));
|
||||
defer chapter_dir.close();
|
||||
|
||||
var it = chapter_dir.iterate();
|
||||
while (it.next() catch continue) |chapter_dir_entry| {
|
||||
while (it.next() catch |err| @panic(@errorName(err))) |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;
|
||||
const exe_mod = buildExeModuleFromChapterDirEntry(b, target, optimize, chapter_dir_name, chapter_dir_entry) catch |err| @panic(@errorName(err));
|
||||
addTestStepToExeModule(b, test_step, exe_mod, test_filters);
|
||||
}
|
||||
}
|
||||
@@ -64,30 +56,6 @@ fn buildExeModuleFromChapterDirEntry(
|
||||
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]; // Extract the base name from xxx.zig
|
||||
|
||||
// Temporarily enable only the updated examples listed below; enable the rest once they have been migrated
|
||||
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,
|
||||
|
||||
@@ -1,44 +0,0 @@
|
||||
// File: climbing_stairs_backtrack.zig
|
||||
// Created Time: 2023-07-15
|
||||
// Author: codingonion (coderonion@gmail.com)
|
||||
|
||||
const std = @import("std");
|
||||
|
||||
// Backtracking
|
||||
fn backtrack(choices: []i32, state: i32, n: i32, res: std.ArrayList(i32)) void {
|
||||
// When step n is reached, increase the number of ways by 1
|
||||
if (state == n) {
|
||||
res.items[0] = res.items[0] + 1;
|
||||
}
|
||||
// Iterate over all choices
|
||||
for (choices) |choice| {
|
||||
// Prune: do not go beyond step n
|
||||
if (state + choice > n) {
|
||||
continue;
|
||||
}
|
||||
// Try: make a choice and update the state
|
||||
backtrack(choices, state + choice, n, res);
|
||||
// Backtrack
|
||||
}
|
||||
}
|
||||
|
||||
// Climbing stairs: backtracking
|
||||
fn climbingStairsBacktrack(n: usize) !i32 {
|
||||
var choices = [_]i32{ 1, 2 }; // Choose to climb 1 or 2 steps
|
||||
var state: i32 = 0; // Start climbing from step 0
|
||||
var res = std.ArrayList(i32).init(std.heap.page_allocator);
|
||||
defer res.deinit();
|
||||
try res.append(0); // Use res.items[0] to record the number of solutions
|
||||
backtrack(&choices, state, @intCast(n), res);
|
||||
return res.items[0];
|
||||
}
|
||||
|
||||
// Driver code
|
||||
pub fn main() !void {
|
||||
var n: usize = 9;
|
||||
|
||||
var res = try climbingStairsBacktrack(n);
|
||||
std.debug.print("Ways to climb {} stairs: {}\n", .{ n, res });
|
||||
|
||||
_ = try std.io.getStdIn().reader().readByte();
|
||||
}
|
||||
@@ -1,35 +0,0 @@
|
||||
// File: climbing_stairs_constraint_dp.zig
|
||||
// Created Time: 2023-07-15
|
||||
// Author: codingonion (coderonion@gmail.com)
|
||||
|
||||
const std = @import("std");
|
||||
|
||||
// Climbing stairs with constraints: dynamic programming
|
||||
fn climbingStairsConstraintDP(comptime n: usize) i32 {
|
||||
if (n == 1 or n == 2) {
|
||||
return 1;
|
||||
}
|
||||
// Initialize the dp table to store subproblem solutions
|
||||
var dp = [_][3]i32{ [_]i32{ -1, -1, -1 } } ** (n + 1);
|
||||
// Initial states: set the solutions to the smallest subproblems
|
||||
dp[1][1] = 1;
|
||||
dp[1][2] = 0;
|
||||
dp[2][1] = 0;
|
||||
dp[2][2] = 1;
|
||||
// State transitions: solve progressively larger subproblems using smaller ones
|
||||
for (3..n + 1) |i| {
|
||||
dp[i][1] = dp[i - 1][2];
|
||||
dp[i][2] = dp[i - 2][1] + dp[i - 2][2];
|
||||
}
|
||||
return dp[n][1] + dp[n][2];
|
||||
}
|
||||
|
||||
// Driver code
|
||||
pub fn main() !void {
|
||||
comptime var n: usize = 9;
|
||||
|
||||
var res = climbingStairsConstraintDP(n);
|
||||
std.debug.print("Ways to climb {} stairs: {}\n", .{ n, res });
|
||||
|
||||
_ = try std.io.getStdIn().reader().readByte();
|
||||
}
|
||||
@@ -1,31 +0,0 @@
|
||||
// File: climbing_stairs_dfs.zig
|
||||
// Created Time: 2023-07-15
|
||||
// Author: codingonion (coderonion@gmail.com)
|
||||
|
||||
const std = @import("std");
|
||||
|
||||
// Search
|
||||
fn dfs(i: usize) i32 {
|
||||
// The values of dp[1] and dp[2] are known; return them
|
||||
if (i == 1 or i == 2) {
|
||||
return @intCast(i);
|
||||
}
|
||||
// dp[i] = dp[i-1] + dp[i-2]
|
||||
var count = dfs(i - 1) + dfs(i - 2);
|
||||
return count;
|
||||
}
|
||||
|
||||
// Climbing stairs: search
|
||||
fn climbingStairsDFS(comptime n: usize) i32 {
|
||||
return dfs(n);
|
||||
}
|
||||
|
||||
// Driver code
|
||||
pub fn main() !void {
|
||||
comptime var n: usize = 9;
|
||||
|
||||
var res = climbingStairsDFS(n);
|
||||
std.debug.print("Ways to climb {} stairs: {}\n", .{ n, res });
|
||||
|
||||
_ = try std.io.getStdIn().reader().readByte();
|
||||
}
|
||||
@@ -1,39 +0,0 @@
|
||||
// File: climbing_stairs_dfs_mem.zig
|
||||
// Created Time: 2023-07-15
|
||||
// Author: codingonion (coderonion@gmail.com)
|
||||
|
||||
const std = @import("std");
|
||||
|
||||
// Memoized search
|
||||
fn dfs(i: usize, mem: []i32) i32 {
|
||||
// The values of dp[1] and dp[2] are known; return them
|
||||
if (i == 1 or i == 2) {
|
||||
return @intCast(i);
|
||||
}
|
||||
// If dp[i] has been recorded, return it directly
|
||||
if (mem[i] != -1) {
|
||||
return mem[i];
|
||||
}
|
||||
// dp[i] = dp[i-1] + dp[i-2]
|
||||
var count = dfs(i - 1, mem) + dfs(i - 2, mem);
|
||||
// Record dp[i]
|
||||
mem[i] = count;
|
||||
return count;
|
||||
}
|
||||
|
||||
// Climbing stairs: memoized search
|
||||
fn climbingStairsDFSMem(comptime n: usize) i32 {
|
||||
// mem[i] stores the number of ways to reach step i; -1 means no result has been recorded
|
||||
var mem = [_]i32{ -1 } ** (n + 1);
|
||||
return dfs(n, &mem);
|
||||
}
|
||||
|
||||
// Driver code
|
||||
pub fn main() !void {
|
||||
comptime var n: usize = 9;
|
||||
|
||||
var res = climbingStairsDFSMem(n);
|
||||
std.debug.print("Ways to climb {} stairs: {}\n", .{ n, res });
|
||||
|
||||
_ = try std.io.getStdIn().reader().readByte();
|
||||
}
|
||||
@@ -1,51 +0,0 @@
|
||||
// File: climbing_stairs_dp.zig
|
||||
// Created Time: 2023-07-15
|
||||
// Author: codingonion (coderonion@gmail.com)
|
||||
|
||||
const std = @import("std");
|
||||
|
||||
// Climbing stairs: dynamic programming
|
||||
fn climbingStairsDP(comptime n: usize) i32 {
|
||||
// The values of dp[1] and dp[2] are known; return them
|
||||
if (n == 1 or n == 2) {
|
||||
return @intCast(n);
|
||||
}
|
||||
// Initialize the dp table to store subproblem solutions
|
||||
var dp = [_]i32{-1} ** (n + 1);
|
||||
// Initial states: set the solutions to the smallest subproblems
|
||||
dp[1] = 1;
|
||||
dp[2] = 2;
|
||||
// State transitions: solve progressively larger subproblems using smaller ones
|
||||
for (3..n + 1) |i| {
|
||||
dp[i] = dp[i - 1] + dp[i - 2];
|
||||
}
|
||||
return dp[n];
|
||||
}
|
||||
|
||||
// Climbing stairs: space-optimized dynamic programming
|
||||
fn climbingStairsDPComp(comptime n: usize) i32 {
|
||||
if (n == 1 or n == 2) {
|
||||
return @intCast(n);
|
||||
}
|
||||
var a: i32 = 1;
|
||||
var b: i32 = 2;
|
||||
for (3..n + 1) |_| {
|
||||
var tmp = b;
|
||||
b = a + b;
|
||||
a = tmp;
|
||||
}
|
||||
return b;
|
||||
}
|
||||
|
||||
// Driver code
|
||||
pub fn main() !void {
|
||||
comptime var n: usize = 9;
|
||||
|
||||
var res = climbingStairsDP(n);
|
||||
std.debug.print("Ways to climb {} stairs: {}\n", .{ n, res });
|
||||
|
||||
res = climbingStairsDPComp(n);
|
||||
std.debug.print("Ways to climb {} stairs: {}\n", .{ n, res });
|
||||
|
||||
_ = try std.io.getStdIn().reader().readByte();
|
||||
}
|
||||
@@ -1,77 +0,0 @@
|
||||
// File: coin_change.zig
|
||||
// Created Time: 2023-07-15
|
||||
// Author: codingonion (coderonion@gmail.com)
|
||||
|
||||
const std = @import("std");
|
||||
|
||||
// Coin change: dynamic programming
|
||||
fn coinChangeDP(comptime coins: []i32, comptime amt: usize) i32 {
|
||||
comptime var n = coins.len;
|
||||
comptime var max = amt + 1;
|
||||
// Initialize the dp table
|
||||
var dp = [_][amt + 1]i32{[_]i32{0} ** (amt + 1)} ** (n + 1);
|
||||
// State transitions: first row and first column
|
||||
for (1..amt + 1) |a| {
|
||||
dp[0][a] = max;
|
||||
}
|
||||
// State transitions: remaining rows and columns
|
||||
for (1..n + 1) |i| {
|
||||
for (1..amt + 1) |a| {
|
||||
if (coins[i - 1] > @as(i32, @intCast(a))) {
|
||||
// If the coin exceeds the target amount, do not choose coin i
|
||||
dp[i][a] = dp[i - 1][a];
|
||||
} else {
|
||||
// Take the smaller result of not choosing and choosing coin i
|
||||
dp[i][a] = @min(dp[i - 1][a], dp[i][a - @as(usize, @intCast(coins[i - 1]))] + 1);
|
||||
}
|
||||
}
|
||||
}
|
||||
if (dp[n][amt] != max) {
|
||||
return @intCast(dp[n][amt]);
|
||||
} else {
|
||||
return -1;
|
||||
}
|
||||
}
|
||||
|
||||
// Coin change: space-optimized dynamic programming
|
||||
fn coinChangeDPComp(comptime coins: []i32, comptime amt: usize) i32 {
|
||||
comptime var n = coins.len;
|
||||
comptime var max = amt + 1;
|
||||
// Initialize the dp table
|
||||
var dp = [_]i32{0} ** (amt + 1);
|
||||
@memset(&dp, max);
|
||||
dp[0] = 0;
|
||||
// State transitions
|
||||
for (1..n + 1) |i| {
|
||||
for (1..amt + 1) |a| {
|
||||
if (coins[i - 1] > @as(i32, @intCast(a))) {
|
||||
// If the coin exceeds the target amount, do not choose coin i
|
||||
dp[a] = dp[a];
|
||||
} else {
|
||||
// Take the smaller result of not choosing and choosing coin i
|
||||
dp[a] = @min(dp[a], dp[a - @as(usize, @intCast(coins[i - 1]))] + 1);
|
||||
}
|
||||
}
|
||||
}
|
||||
if (dp[amt] != max) {
|
||||
return @intCast(dp[amt]);
|
||||
} else {
|
||||
return -1;
|
||||
}
|
||||
}
|
||||
|
||||
// Driver code
|
||||
pub fn main() !void {
|
||||
comptime var coins = [_]i32{ 1, 2, 5 };
|
||||
comptime var amt: usize = 4;
|
||||
|
||||
// Dynamic programming
|
||||
var res = coinChangeDP(&coins, amt);
|
||||
std.debug.print("Minimum number of coins needed for the target amount: {}\n", .{res});
|
||||
|
||||
// Space-optimized dynamic programming
|
||||
res = coinChangeDPComp(&coins, amt);
|
||||
std.debug.print("Minimum number of coins needed for the target amount: {}\n", .{res});
|
||||
|
||||
_ = try std.io.getStdIn().reader().readByte();
|
||||
}
|
||||
@@ -1,66 +0,0 @@
|
||||
// File: coin_change_ii.zig
|
||||
// Created Time: 2023-07-15
|
||||
// Author: codingonion (coderonion@gmail.com)
|
||||
|
||||
const std = @import("std");
|
||||
|
||||
// Coin change II: dynamic programming
|
||||
fn coinChangeIIDP(comptime coins: []i32, comptime amt: usize) i32 {
|
||||
comptime var n = coins.len;
|
||||
// Initialize the dp table
|
||||
var dp = [_][amt + 1]i32{[_]i32{0} ** (amt + 1)} ** (n + 1);
|
||||
// Initialize the first column
|
||||
for (0..n + 1) |i| {
|
||||
dp[i][0] = 1;
|
||||
}
|
||||
// State transitions
|
||||
for (1..n + 1) |i| {
|
||||
for (1..amt + 1) |a| {
|
||||
if (coins[i - 1] > @as(i32, @intCast(a))) {
|
||||
// If the coin exceeds the target amount, do not choose coin i
|
||||
dp[i][a] = dp[i - 1][a];
|
||||
} else {
|
||||
// Add the counts for excluding coin i and including coin i
|
||||
dp[i][a] = dp[i - 1][a] + dp[i][a - @as(usize, @intCast(coins[i - 1]))];
|
||||
}
|
||||
}
|
||||
}
|
||||
return dp[n][amt];
|
||||
}
|
||||
|
||||
// Coin change II: space-optimized dynamic programming
|
||||
fn coinChangeIIDPComp(comptime coins: []i32, comptime amt: usize) i32 {
|
||||
comptime var n = coins.len;
|
||||
// Initialize the dp table
|
||||
var dp = [_]i32{0} ** (amt + 1);
|
||||
dp[0] = 1;
|
||||
// State transitions
|
||||
for (1..n + 1) |i| {
|
||||
for (1..amt + 1) |a| {
|
||||
if (coins[i - 1] > @as(i32, @intCast(a))) {
|
||||
// If the coin exceeds the target amount, do not choose coin i
|
||||
dp[a] = dp[a];
|
||||
} else {
|
||||
// Add the counts for excluding coin i and including coin i
|
||||
dp[a] = dp[a] + dp[a - @as(usize, @intCast(coins[i - 1]))];
|
||||
}
|
||||
}
|
||||
}
|
||||
return dp[amt];
|
||||
}
|
||||
|
||||
// Driver code
|
||||
pub fn main() !void {
|
||||
comptime var coins = [_]i32{ 1, 2, 5 };
|
||||
comptime var amt: usize = 5;
|
||||
|
||||
// Dynamic programming
|
||||
var res = coinChangeIIDP(&coins, amt);
|
||||
std.debug.print("Number of coin combinations for the target amount: {}\n", .{res});
|
||||
|
||||
// Space-optimized dynamic programming
|
||||
res = coinChangeIIDPComp(&coins, amt);
|
||||
std.debug.print("Number of coin combinations for the target amount: {}\n", .{res});
|
||||
|
||||
_ = try std.io.getStdIn().reader().readByte();
|
||||
}
|
||||
@@ -1,146 +0,0 @@
|
||||
// File: edit_distance.zig
|
||||
// Created Time: 2023-07-15
|
||||
// Author: codingonion (coderonion@gmail.com)
|
||||
|
||||
const std = @import("std");
|
||||
|
||||
// Edit distance: brute-force search
|
||||
fn editDistanceDFS(comptime s: []const u8, comptime t: []const u8, i: usize, j: usize) i32 {
|
||||
// If both prefixes s[0..i] and t[0..j] are empty, return 0
|
||||
if (i == 0 and j == 0) {
|
||||
return 0;
|
||||
}
|
||||
// If the prefix s[0..i] is empty, return the length j of the other prefix
|
||||
if (i == 0) {
|
||||
return @intCast(j);
|
||||
}
|
||||
// If the prefix t[0..j] is empty, return the length i of the other prefix
|
||||
if (j == 0) {
|
||||
return @intCast(i);
|
||||
}
|
||||
// If the two characters are equal, skip both of them
|
||||
if (s[i - 1] == t[j - 1]) {
|
||||
return editDistanceDFS(s, t, i - 1, j - 1);
|
||||
}
|
||||
// Minimum edits = the minimum among the insertion, deletion, and replacement subproblems + 1
|
||||
var insert = editDistanceDFS(s, t, i, j - 1);
|
||||
var delete = editDistanceDFS(s, t, i - 1, j);
|
||||
var replace = editDistanceDFS(s, t, i - 1, j - 1);
|
||||
// Return the minimum number of edits
|
||||
return @min(@min(insert, delete), replace) + 1;
|
||||
}
|
||||
|
||||
// Edit distance: memoized search
|
||||
fn editDistanceDFSMem(comptime s: []const u8, comptime t: []const u8, mem: anytype, i: usize, j: usize) i32 {
|
||||
// If both prefixes s[0..i] and t[0..j] are empty, return 0
|
||||
if (i == 0 and j == 0) {
|
||||
return 0;
|
||||
}
|
||||
// If the prefix s[0..i] is empty, return the length j of the other prefix
|
||||
if (i == 0) {
|
||||
return @intCast(j);
|
||||
}
|
||||
// If the prefix t[0..j] is empty, return the length i of the other prefix
|
||||
if (j == 0) {
|
||||
return @intCast(i);
|
||||
}
|
||||
// If a result has already been recorded, return it directly
|
||||
if (mem[i][j] != -1) {
|
||||
return mem[i][j];
|
||||
}
|
||||
// If the two characters are equal, skip both of them
|
||||
if (s[i - 1] == t[j - 1]) {
|
||||
return editDistanceDFSMem(s, t, mem, i - 1, j - 1);
|
||||
}
|
||||
// Minimum edits = the minimum among the insertion, deletion, and replacement subproblems + 1
|
||||
var insert = editDistanceDFSMem(s, t, mem, i, j - 1);
|
||||
var delete = editDistanceDFSMem(s, t, mem, i - 1, j);
|
||||
var replace = editDistanceDFSMem(s, t, mem, i - 1, j - 1);
|
||||
// Record and return the minimum number of edits
|
||||
mem[i][j] = @min(@min(insert, delete), replace) + 1;
|
||||
return mem[i][j];
|
||||
}
|
||||
|
||||
// Edit distance: dynamic programming
|
||||
fn editDistanceDP(comptime s: []const u8, comptime t: []const u8) i32 {
|
||||
comptime var n = s.len;
|
||||
comptime var m = t.len;
|
||||
var dp = [_][m + 1]i32{[_]i32{0} ** (m + 1)} ** (n + 1);
|
||||
// State transitions: first row and first column
|
||||
for (1..n + 1) |i| {
|
||||
dp[i][0] = @intCast(i);
|
||||
}
|
||||
for (1..m + 1) |j| {
|
||||
dp[0][j] = @intCast(j);
|
||||
}
|
||||
// State transitions: remaining rows and columns
|
||||
for (1..n + 1) |i| {
|
||||
for (1..m + 1) |j| {
|
||||
if (s[i - 1] == t[j - 1]) {
|
||||
// If the two characters are equal, skip both of them
|
||||
dp[i][j] = dp[i - 1][j - 1];
|
||||
} else {
|
||||
// Minimum edits = the minimum among the insertion, deletion, and replacement subproblems + 1
|
||||
dp[i][j] = @min(@min(dp[i][j - 1], dp[i - 1][j]), dp[i - 1][j - 1]) + 1;
|
||||
}
|
||||
}
|
||||
}
|
||||
return dp[n][m];
|
||||
}
|
||||
|
||||
// Edit distance: space-optimized dynamic programming
|
||||
fn editDistanceDPComp(comptime s: []const u8, comptime t: []const u8) i32 {
|
||||
comptime var n = s.len;
|
||||
comptime var m = t.len;
|
||||
var dp = [_]i32{0} ** (m + 1);
|
||||
// State transitions: first row
|
||||
for (1..m + 1) |j| {
|
||||
dp[j] = @intCast(j);
|
||||
}
|
||||
// State transitions: remaining rows
|
||||
for (1..n + 1) |i| {
|
||||
// State transitions: first column
|
||||
var leftup = dp[0]; // Temporarily store dp[i-1, j-1]
|
||||
dp[0] = @intCast(i);
|
||||
// State transitions: remaining columns
|
||||
for (1..m + 1) |j| {
|
||||
var temp = dp[j];
|
||||
if (s[i - 1] == t[j - 1]) {
|
||||
// If the two characters are equal, skip both of them
|
||||
dp[j] = leftup;
|
||||
} else {
|
||||
// Minimum edits = the minimum among the insertion, deletion, and replacement subproblems + 1
|
||||
dp[j] = @min(@min(dp[j - 1], dp[j]), leftup) + 1;
|
||||
}
|
||||
leftup = temp; // Update to dp[i-1, j-1] for the next iteration
|
||||
}
|
||||
}
|
||||
return dp[m];
|
||||
}
|
||||
|
||||
// Driver code
|
||||
pub fn main() !void {
|
||||
const s = "bag";
|
||||
const t = "pack";
|
||||
comptime var n = s.len;
|
||||
comptime var m = t.len;
|
||||
|
||||
// Brute-force search
|
||||
var res = editDistanceDFS(s, t, n, m);
|
||||
std.debug.print("Changing {s} to {s} requires at least {} edits\n", .{ s, t, res });
|
||||
|
||||
// Memoized search
|
||||
var mem = [_][m + 1]i32{[_]i32{-1} ** (m + 1)} ** (n + 1);
|
||||
res = editDistanceDFSMem(s, t, @constCast(&mem), n, m);
|
||||
std.debug.print("Changing {s} to {s} requires at least {} edits\n", .{ s, t, res });
|
||||
|
||||
// Dynamic programming
|
||||
res = editDistanceDP(s, t);
|
||||
std.debug.print("Changing {s} to {s} requires at least {} edits\n", .{ s, t, res });
|
||||
|
||||
// Space-optimized dynamic programming
|
||||
res = editDistanceDPComp(s, t);
|
||||
std.debug.print("Changing {s} to {s} requires at least {} edits\n", .{ s, t, res });
|
||||
|
||||
_ = try std.io.getStdIn().reader().readByte();
|
||||
}
|
||||
@@ -1,110 +0,0 @@
|
||||
// File: knapsack.zig
|
||||
// Created Time: 2023-07-15
|
||||
// Author: codingonion (coderonion@gmail.com)
|
||||
|
||||
const std = @import("std");
|
||||
|
||||
// 0-1 knapsack: brute-force search
|
||||
fn knapsackDFS(wgt: []i32, val: []i32, i: usize, c: usize) i32 {
|
||||
// If all items have been considered or no capacity remains, return value 0
|
||||
if (i == 0 or c == 0) {
|
||||
return 0;
|
||||
}
|
||||
// If the item exceeds the remaining capacity, it must be excluded
|
||||
if (wgt[i - 1] > c) {
|
||||
return knapsackDFS(wgt, val, i - 1, c);
|
||||
}
|
||||
// Calculate the maximum values obtained by excluding and including item i
|
||||
var no = knapsackDFS(wgt, val, i - 1, c);
|
||||
var yes = knapsackDFS(wgt, val, i - 1, c - @as(usize, @intCast(wgt[i - 1]))) + val[i - 1];
|
||||
// Return the larger value from the two choices
|
||||
return @max(no, yes);
|
||||
}
|
||||
|
||||
// 0-1 knapsack: memoized search
|
||||
fn knapsackDFSMem(wgt: []i32, val: []i32, mem: anytype, i: usize, c: usize) i32 {
|
||||
// If all items have been considered or no capacity remains, return value 0
|
||||
if (i == 0 or c == 0) {
|
||||
return 0;
|
||||
}
|
||||
// If a result has already been recorded, return it directly
|
||||
if (mem[i][c] != -1) {
|
||||
return mem[i][c];
|
||||
}
|
||||
// If the item exceeds the remaining capacity, it must be excluded
|
||||
if (wgt[i - 1] > c) {
|
||||
return knapsackDFSMem(wgt, val, mem, i - 1, c);
|
||||
}
|
||||
// Calculate the maximum values obtained by excluding and including item i
|
||||
var no = knapsackDFSMem(wgt, val, mem, i - 1, c);
|
||||
var yes = knapsackDFSMem(wgt, val, mem, i - 1, c - @as(usize, @intCast(wgt[i - 1]))) + val[i - 1];
|
||||
// Record and return the larger value from the two choices
|
||||
mem[i][c] = @max(no, yes);
|
||||
return mem[i][c];
|
||||
}
|
||||
|
||||
// 0-1 knapsack: dynamic programming
|
||||
fn knapsackDP(comptime wgt: []i32, val: []i32, comptime cap: usize) i32 {
|
||||
comptime var n = wgt.len;
|
||||
// Initialize the dp table
|
||||
var dp = [_][cap + 1]i32{[_]i32{0} ** (cap + 1)} ** (n + 1);
|
||||
// State transitions
|
||||
for (1..n + 1) |i| {
|
||||
for (1..cap + 1) |c| {
|
||||
if (wgt[i - 1] > c) {
|
||||
// If item i exceeds the remaining capacity, do not choose it
|
||||
dp[i][c] = dp[i - 1][c];
|
||||
} else {
|
||||
// Take the larger value obtained by excluding and including item i
|
||||
dp[i][c] = @max(dp[i - 1][c], dp[i - 1][c - @as(usize, @intCast(wgt[i - 1]))] + val[i - 1]);
|
||||
}
|
||||
}
|
||||
}
|
||||
return dp[n][cap];
|
||||
}
|
||||
|
||||
// 0-1 knapsack: space-optimized dynamic programming
|
||||
fn knapsackDPComp(wgt: []i32, val: []i32, comptime cap: usize) i32 {
|
||||
var n = wgt.len;
|
||||
// Initialize the dp table
|
||||
var dp = [_]i32{0} ** (cap + 1);
|
||||
// State transitions
|
||||
for (1..n + 1) |i| {
|
||||
// Traverse in decreasing order
|
||||
var c = cap;
|
||||
while (c > 0) : (c -= 1) {
|
||||
if (wgt[i - 1] < c) {
|
||||
// Take the larger value obtained by excluding and including item i
|
||||
dp[c] = @max(dp[c], dp[c - @as(usize, @intCast(wgt[i - 1]))] + val[i - 1]);
|
||||
}
|
||||
}
|
||||
}
|
||||
return dp[cap];
|
||||
}
|
||||
|
||||
// Driver code
|
||||
pub fn main() !void {
|
||||
comptime var wgt = [_]i32{ 10, 20, 30, 40, 50 };
|
||||
comptime var val = [_]i32{ 50, 120, 150, 210, 240 };
|
||||
comptime var cap = 50;
|
||||
comptime var n = wgt.len;
|
||||
|
||||
// Brute-force search
|
||||
var res = knapsackDFS(&wgt, &val, n, cap);
|
||||
std.debug.print("Maximum total item value within the knapsack capacity: {}\n", .{res});
|
||||
|
||||
// Memoized search
|
||||
var mem = [_][cap + 1]i32{[_]i32{-1} ** (cap + 1)} ** (n + 1);
|
||||
res = knapsackDFSMem(&wgt, &val, @constCast(&mem), n, cap);
|
||||
std.debug.print("Maximum total item value within the knapsack capacity: {}\n", .{res});
|
||||
|
||||
// Dynamic programming
|
||||
res = knapsackDP(&wgt, &val, cap);
|
||||
std.debug.print("Maximum total item value within the knapsack capacity: {}\n", .{res});
|
||||
|
||||
// Space-optimized dynamic programming
|
||||
res = knapsackDPComp(&wgt, &val, cap);
|
||||
std.debug.print("Maximum total item value within the knapsack capacity: {}\n", .{res});
|
||||
|
||||
_ = try std.io.getStdIn().reader().readByte();
|
||||
}
|
||||
@@ -1,54 +0,0 @@
|
||||
// File: min_cost_climbing_stairs_dp.zig
|
||||
// Created Time: 2023-07-15
|
||||
// Author: codingonion (coderonion@gmail.com)
|
||||
|
||||
const std = @import("std");
|
||||
|
||||
// Minimum cost to climb stairs: dynamic programming
|
||||
fn minCostClimbingStairsDP(comptime cost: []i32) i32 {
|
||||
comptime var n = cost.len - 1;
|
||||
if (n == 1 or n == 2) {
|
||||
return cost[n];
|
||||
}
|
||||
// Initialize the dp table to store subproblem solutions
|
||||
var dp = [_]i32{-1} ** (n + 1);
|
||||
// Initial states: set the solutions to the smallest subproblems
|
||||
dp[1] = cost[1];
|
||||
dp[2] = cost[2];
|
||||
// State transitions: solve progressively larger subproblems using smaller ones
|
||||
for (3..n + 1) |i| {
|
||||
dp[i] = @min(dp[i - 1], dp[i - 2]) + cost[i];
|
||||
}
|
||||
return dp[n];
|
||||
}
|
||||
|
||||
// Minimum cost to climb stairs: space-optimized dynamic programming
|
||||
fn minCostClimbingStairsDPComp(cost: []i32) i32 {
|
||||
var n = cost.len - 1;
|
||||
if (n == 1 or n == 2) {
|
||||
return cost[n];
|
||||
}
|
||||
var a = cost[1];
|
||||
var b = cost[2];
|
||||
// State transitions: solve progressively larger subproblems using smaller ones
|
||||
for (3..n + 1) |i| {
|
||||
var tmp = b;
|
||||
b = @min(a, tmp) + cost[i];
|
||||
a = tmp;
|
||||
}
|
||||
return b;
|
||||
}
|
||||
|
||||
// Driver code
|
||||
pub fn main() !void {
|
||||
comptime var cost = [_]i32{ 0, 1, 10, 1, 1, 1, 10, 1, 1, 10, 1 };
|
||||
std.debug.print("Input stair costs: {any}\n", .{cost});
|
||||
|
||||
var res = minCostClimbingStairsDP(&cost);
|
||||
std.debug.print("Minimum cost to climb the stairs: {}\n", .{res});
|
||||
|
||||
res = minCostClimbingStairsDPComp(&cost);
|
||||
std.debug.print("Minimum cost to climb the stairs: {}\n", .{res});
|
||||
|
||||
_ = try std.io.getStdIn().reader().readByte();
|
||||
}
|
||||
@@ -1,122 +0,0 @@
|
||||
// File: min_path_sum.zig
|
||||
// Created Time: 2023-07-15
|
||||
// Author: codingonion (coderonion@gmail.com)
|
||||
|
||||
const std = @import("std");
|
||||
|
||||
// Minimum path sum: brute-force search
|
||||
fn minPathSumDFS(grid: anytype, i: i32, j: i32) i32 {
|
||||
// Stop searching at the top-left cell
|
||||
if (i == 0 and j == 0) {
|
||||
return grid[0][0];
|
||||
}
|
||||
// If a row or column index is out of bounds, use the maximum i32 value to represent infinite cost
|
||||
if (i < 0 or j < 0) {
|
||||
return std.math.maxInt(i32);
|
||||
}
|
||||
// Calculate the minimum path costs from the top-left corner to (i-1, j) and (i, j-1)
|
||||
var up = minPathSumDFS(grid, i - 1, j);
|
||||
var left = minPathSumDFS(grid, i, j - 1);
|
||||
// Return the minimum path cost from the top-left corner to (i, j)
|
||||
return @min(left, up) + grid[@as(usize, @intCast(i))][@as(usize, @intCast(j))];
|
||||
}
|
||||
|
||||
// Minimum path sum: memoized search
|
||||
fn minPathSumDFSMem(grid: anytype, mem: anytype, i: i32, j: i32) i32 {
|
||||
// Stop searching at the top-left cell
|
||||
if (i == 0 and j == 0) {
|
||||
return grid[0][0];
|
||||
}
|
||||
// If a row or column index is out of bounds, use the maximum i32 value to represent infinite cost
|
||||
if (i < 0 or j < 0) {
|
||||
return std.math.maxInt(i32);
|
||||
}
|
||||
// If a result has already been recorded, return it directly
|
||||
if (mem[@as(usize, @intCast(i))][@as(usize, @intCast(j))] != -1) {
|
||||
return mem[@as(usize, @intCast(i))][@as(usize, @intCast(j))];
|
||||
}
|
||||
// Calculate the minimum path costs from the top-left corner to (i-1, j) and (i, j-1)
|
||||
var up = minPathSumDFSMem(grid, mem, i - 1, j);
|
||||
var left = minPathSumDFSMem(grid, mem, i, j - 1);
|
||||
// Return the minimum path cost from the top-left corner to (i, j)
|
||||
// Record and return the minimum path cost from the top-left corner to (i, j)
|
||||
mem[@as(usize, @intCast(i))][@as(usize, @intCast(j))] = @min(left, up) + grid[@as(usize, @intCast(i))][@as(usize, @intCast(j))];
|
||||
return mem[@as(usize, @intCast(i))][@as(usize, @intCast(j))];
|
||||
}
|
||||
|
||||
// Minimum path sum: dynamic programming
|
||||
fn minPathSumDP(comptime grid: anytype) i32 {
|
||||
comptime var n = grid.len;
|
||||
comptime var m = grid[0].len;
|
||||
// Initialize the dp table
|
||||
var dp = [_][m]i32{[_]i32{0} ** m} ** n;
|
||||
dp[0][0] = grid[0][0];
|
||||
// State transitions: first row
|
||||
for (1..m) |j| {
|
||||
dp[0][j] = dp[0][j - 1] + grid[0][j];
|
||||
}
|
||||
// State transitions: first column
|
||||
for (1..n) |i| {
|
||||
dp[i][0] = dp[i - 1][0] + grid[i][0];
|
||||
}
|
||||
// State transitions: remaining rows and columns
|
||||
for (1..n) |i| {
|
||||
for (1..m) |j| {
|
||||
dp[i][j] = @min(dp[i][j - 1], dp[i - 1][j]) + grid[i][j];
|
||||
}
|
||||
}
|
||||
return dp[n - 1][m - 1];
|
||||
}
|
||||
|
||||
// Minimum path sum: space-optimized dynamic programming
|
||||
fn minPathSumDPComp(comptime grid: anytype) i32 {
|
||||
comptime var n = grid.len;
|
||||
comptime var m = grid[0].len;
|
||||
// Initialize the dp table
|
||||
var dp = [_]i32{0} ** m;
|
||||
// State transitions: first row
|
||||
dp[0] = grid[0][0];
|
||||
for (1..m) |j| {
|
||||
dp[j] = dp[j - 1] + grid[0][j];
|
||||
}
|
||||
// State transitions: remaining rows
|
||||
for (1..n) |i| {
|
||||
// State transitions: first column
|
||||
dp[0] = dp[0] + grid[i][0];
|
||||
for (1..m) |j| {
|
||||
dp[j] = @min(dp[j - 1], dp[j]) + grid[i][j];
|
||||
}
|
||||
}
|
||||
return dp[m - 1];
|
||||
}
|
||||
|
||||
// Driver code
|
||||
pub fn main() !void {
|
||||
comptime var grid = [_][4]i32{
|
||||
[_]i32{ 1, 3, 1, 5 },
|
||||
[_]i32{ 2, 2, 4, 2 },
|
||||
[_]i32{ 5, 3, 2, 1 },
|
||||
[_]i32{ 4, 3, 5, 2 },
|
||||
};
|
||||
comptime var n = grid.len;
|
||||
comptime var m = grid[0].len;
|
||||
|
||||
// Brute-force search
|
||||
var res = minPathSumDFS(&grid, n - 1, m - 1);
|
||||
std.debug.print("Minimum path sum from the top-left to the bottom-right corner: {}\n", .{res});
|
||||
|
||||
// Memoized search
|
||||
var mem = [_][m]i32{[_]i32{-1} ** m} ** n;
|
||||
res = minPathSumDFSMem(&grid, &mem, n - 1, m - 1);
|
||||
std.debug.print("Minimum path sum from the top-left to the bottom-right corner: {}\n", .{res});
|
||||
|
||||
// Dynamic programming
|
||||
res = minPathSumDP(&grid);
|
||||
std.debug.print("Minimum path sum from the top-left to the bottom-right corner: {}\n", .{res});
|
||||
|
||||
// Space-optimized dynamic programming
|
||||
res = minPathSumDPComp(&grid);
|
||||
std.debug.print("Minimum path sum from the top-left to the bottom-right corner: {}\n", .{res});
|
||||
|
||||
_ = try std.io.getStdIn().reader().readByte();
|
||||
}
|
||||
@@ -1,62 +0,0 @@
|
||||
// File: unbounded_knapsack.zig
|
||||
// Created Time: 2023-07-15
|
||||
// Author: codingonion (coderonion@gmail.com)
|
||||
|
||||
const std = @import("std");
|
||||
|
||||
// Unbounded knapsack: dynamic programming
|
||||
fn unboundedKnapsackDP(comptime wgt: []i32, val: []i32, comptime cap: usize) i32 {
|
||||
comptime var n = wgt.len;
|
||||
// Initialize the dp table
|
||||
var dp = [_][cap + 1]i32{[_]i32{0} ** (cap + 1)} ** (n + 1);
|
||||
// State transitions
|
||||
for (1..n + 1) |i| {
|
||||
for (1..cap + 1) |c| {
|
||||
if (wgt[i - 1] > c) {
|
||||
// If item i exceeds the remaining capacity, do not choose it
|
||||
dp[i][c] = dp[i - 1][c];
|
||||
} else {
|
||||
// Take the larger value obtained by excluding and including item i
|
||||
dp[i][c] = @max(dp[i - 1][c], dp[i][c - @as(usize, @intCast(wgt[i - 1]))] + val[i - 1]);
|
||||
}
|
||||
}
|
||||
}
|
||||
return dp[n][cap];
|
||||
}
|
||||
|
||||
// Unbounded knapsack: space-optimized dynamic programming
|
||||
fn unboundedKnapsackDPComp(comptime wgt: []i32, val: []i32, comptime cap: usize) i32 {
|
||||
comptime var n = wgt.len;
|
||||
// Initialize the dp table
|
||||
var dp = [_]i32{0} ** (cap + 1);
|
||||
// State transitions
|
||||
for (1..n + 1) |i| {
|
||||
for (1..cap + 1) |c| {
|
||||
if (wgt[i - 1] > c) {
|
||||
// If item i exceeds the remaining capacity, do not choose it
|
||||
dp[c] = dp[c];
|
||||
} else {
|
||||
// Take the larger value obtained by excluding and including item i
|
||||
dp[c] = @max(dp[c], dp[c - @as(usize, @intCast(wgt[i - 1]))] + val[i - 1]);
|
||||
}
|
||||
}
|
||||
}
|
||||
return dp[cap];
|
||||
}
|
||||
|
||||
// Driver code
|
||||
pub fn main() !void {
|
||||
comptime var wgt = [_]i32{ 1, 2, 3 };
|
||||
comptime var val = [_]i32{ 5, 11, 15 };
|
||||
comptime var cap = 4;
|
||||
|
||||
// Dynamic programming
|
||||
var res = unboundedKnapsackDP(&wgt, &val, cap);
|
||||
std.debug.print("Maximum total item value within the knapsack capacity: {}\n", .{res});
|
||||
|
||||
// Space-optimized dynamic programming
|
||||
res = unboundedKnapsackDPComp(&wgt, &val, cap);
|
||||
std.debug.print("Maximum total item value within the knapsack capacity: {}\n", .{res});
|
||||
|
||||
_ = try std.io.getStdIn().reader().readByte();
|
||||
}
|
||||
@@ -1,162 +0,0 @@
|
||||
// File: array_hash_map.zig
|
||||
// Created Time: 2023-01-15
|
||||
// Author: codingonion (coderonion@gmail.com)
|
||||
|
||||
const std = @import("std");
|
||||
const inc = @import("include");
|
||||
|
||||
// Key-value pair
|
||||
const Pair = struct {
|
||||
key: usize = undefined,
|
||||
val: []const u8 = undefined,
|
||||
|
||||
pub fn init(key: usize, val: []const u8) Pair {
|
||||
return Pair {
|
||||
.key = key,
|
||||
.val = val,
|
||||
};
|
||||
}
|
||||
};
|
||||
|
||||
// Hash table implemented with an array
|
||||
pub fn ArrayHashMap(comptime T: type) type {
|
||||
return struct {
|
||||
bucket: ?std.ArrayList(?T) = null,
|
||||
mem_allocator: std.mem.Allocator = undefined,
|
||||
|
||||
const Self = @This();
|
||||
|
||||
// Initialize the hash map
|
||||
pub fn init(self: *Self, allocator: std.mem.Allocator) !void {
|
||||
self.mem_allocator = allocator;
|
||||
// Initialize the bucket array with 100 slots
|
||||
self.bucket = std.ArrayList(?T).init(self.mem_allocator);
|
||||
var i: i32 = 0;
|
||||
while (i < 100) : (i += 1) {
|
||||
try self.bucket.?.append(null);
|
||||
}
|
||||
}
|
||||
|
||||
// Deinitialize the hash map
|
||||
pub fn deinit(self: *Self) void {
|
||||
if (self.bucket != null) self.bucket.?.deinit();
|
||||
}
|
||||
|
||||
// Hash function
|
||||
fn hashFunc(key: usize) usize {
|
||||
var index = key % 100;
|
||||
return index;
|
||||
}
|
||||
|
||||
// Lookup operation
|
||||
pub fn get(self: *Self, key: usize) []const u8 {
|
||||
var index = hashFunc(key);
|
||||
var pair = self.bucket.?.items[index];
|
||||
return pair.?.val;
|
||||
}
|
||||
|
||||
// Insert operation
|
||||
pub fn put(self: *Self, key: usize, val: []const u8) !void {
|
||||
var pair = Pair.init(key, val);
|
||||
var index = hashFunc(key);
|
||||
self.bucket.?.items[index] = pair;
|
||||
}
|
||||
|
||||
// Remove operation
|
||||
pub fn remove(self: *Self, key: usize) !void {
|
||||
var index = hashFunc(key);
|
||||
// Set the slot to null to mark it as removed
|
||||
self.bucket.?.items[index] = null;
|
||||
}
|
||||
|
||||
// Get all key-value pairs
|
||||
pub fn pairSet(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;
|
||||
}
|
||||
|
||||
// Get all keys
|
||||
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;
|
||||
}
|
||||
|
||||
// Get all values
|
||||
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;
|
||||
}
|
||||
|
||||
// Print the hash table
|
||||
pub fn print(self: *Self) !void {
|
||||
var entry_set = try self.pairSet();
|
||||
defer entry_set.deinit();
|
||||
for (entry_set.items) |item| {
|
||||
std.debug.print("{} -> {s}\n", .{item.key, item.val});
|
||||
}
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
// Driver code
|
||||
pub fn main() !void {
|
||||
// Initialize the hash table
|
||||
var map = ArrayHashMap(Pair){};
|
||||
try map.init(std.heap.page_allocator);
|
||||
defer map.deinit();
|
||||
|
||||
// Insert operation
|
||||
// Insert the key-value pair (key, value) into the hash table
|
||||
try map.put(12836, "小哈");
|
||||
try map.put(15937, "小啰");
|
||||
try map.put(16750, "小算");
|
||||
try map.put(13276, "小法");
|
||||
try map.put(10583, "小鸭");
|
||||
std.debug.print("\nHash table after insertion:\nKey -> Value\n", .{});
|
||||
try map.print();
|
||||
|
||||
// Lookup operation
|
||||
// Look up key in the hash table to obtain value
|
||||
var name = map.get(15937);
|
||||
std.debug.print("\nLook up student ID 15937: name = {s}\n", .{name});
|
||||
|
||||
// Remove operation
|
||||
// Remove the key-value pair (key, value) from the hash table
|
||||
try map.remove(10583);
|
||||
std.debug.print("\nHash table after removing 10583:\nKey -> Value\n", .{});
|
||||
try map.print();
|
||||
|
||||
// Traverse the hash table
|
||||
std.debug.print("\nIterate over key-value pairs, Key->Value\n", .{});
|
||||
var entry_set = try map.pairSet();
|
||||
for (entry_set.items) |kv| {
|
||||
std.debug.print("{} -> {s}\n", .{kv.key, kv.val});
|
||||
}
|
||||
defer entry_set.deinit();
|
||||
std.debug.print("\nIterate over keys only, Key\n", .{});
|
||||
var key_set = try map.keySet();
|
||||
for (key_set.items) |key| {
|
||||
std.debug.print("{}\n", .{key});
|
||||
}
|
||||
defer key_set.deinit();
|
||||
std.debug.print("\nIterate over the values only\n", .{});
|
||||
var value_set = try map.valueSet();
|
||||
for (value_set.items) |val| {
|
||||
std.debug.print("{s}\n", .{val});
|
||||
}
|
||||
defer value_set.deinit();
|
||||
|
||||
_ = try std.io.getStdIn().reader().readByte();
|
||||
}
|
||||
@@ -1,54 +0,0 @@
|
||||
// File: hash_map.zig
|
||||
// Created Time: 2023-01-13
|
||||
// Author: codingonion (coderonion@gmail.com)
|
||||
|
||||
const std = @import("std");
|
||||
const inc = @import("include");
|
||||
|
||||
// Driver code
|
||||
pub fn main() !void {
|
||||
// Initialize the hash table
|
||||
var map = std.AutoHashMap(i32, []const u8).init(std.heap.page_allocator);
|
||||
// Defer releasing the memory
|
||||
defer map.deinit();
|
||||
|
||||
// Insert operation
|
||||
// Insert the key-value pair (key, value) into the hash table
|
||||
try map.put(12836, "小哈");
|
||||
try map.put(15937, "小啰");
|
||||
try map.put(16750, "小算");
|
||||
try map.put(13276, "小法");
|
||||
try map.put(10583, "小鸭");
|
||||
std.debug.print("\nHash table after insertion:\nKey -> Value\n", .{});
|
||||
inc.PrintUtil.printHashMap(i32, []const u8, map);
|
||||
|
||||
// Lookup operation
|
||||
// Look up key in the hash table to obtain value
|
||||
var name = map.get(15937).?;
|
||||
std.debug.print("\nLook up student ID 15937: name = {s}\n", .{name});
|
||||
|
||||
// Remove operation
|
||||
// Remove the key-value pair (key, value) from the hash table
|
||||
_ = map.remove(10583);
|
||||
std.debug.print("\nHash table after removing 10583:\nKey -> Value\n", .{});
|
||||
inc.PrintUtil.printHashMap(i32, []const u8, map);
|
||||
|
||||
// Traverse the hash table
|
||||
std.debug.print("\nIterate over key-value pairs, Key->Value\n", .{});
|
||||
inc.PrintUtil.printHashMap(i32, []const u8, map);
|
||||
|
||||
std.debug.print("\nIterate over keys only, Key\n", .{});
|
||||
var it = map.iterator();
|
||||
while (it.next()) |kv| {
|
||||
std.debug.print("{}\n", .{kv.key_ptr.*});
|
||||
}
|
||||
|
||||
std.debug.print("\nIterate over the values only\n", .{});
|
||||
it = map.iterator();
|
||||
while (it.next()) |kv| {
|
||||
std.debug.print("{s}\n", .{kv.value_ptr.*});
|
||||
}
|
||||
|
||||
_ = try std.io.getStdIn().reader().readByte();
|
||||
}
|
||||
|
||||
@@ -1,80 +0,0 @@
|
||||
// File: heap.zig
|
||||
// Created Time: 2023-01-14
|
||||
// Author: codingonion (coderonion@gmail.com)
|
||||
|
||||
const std = @import("std");
|
||||
const inc = @import("include");
|
||||
|
||||
fn lessThan(context: void, a: i32, b: i32) std.math.Order {
|
||||
_ = context;
|
||||
return std.math.order(a, b);
|
||||
}
|
||||
|
||||
fn greaterThan(context: void, a: i32, b: i32) std.math.Order {
|
||||
return lessThan(context, a, b).invert();
|
||||
}
|
||||
|
||||
fn testPush(comptime T: type, mem_allocator: std.mem.Allocator, heap: anytype, val: T) !void {
|
||||
try heap.add(val); //Push an element onto the heap
|
||||
std.debug.print("\nAfter pushing {} onto the heap\n", .{val});
|
||||
try inc.PrintUtil.printHeap(T, mem_allocator, heap);
|
||||
}
|
||||
|
||||
fn testPop(comptime T: type, mem_allocator: std.mem.Allocator, heap: anytype) !void {
|
||||
var val = heap.remove(); //Pop the top element from the heap
|
||||
std.debug.print("\nAfter popping the top element {}\n", .{val});
|
||||
try inc.PrintUtil.printHeap(T, mem_allocator, heap);
|
||||
}
|
||||
|
||||
// Driver code
|
||||
pub fn main() !void {
|
||||
// Initialize the allocator
|
||||
var mem_arena = std.heap.ArenaAllocator.init(std.heap.page_allocator);
|
||||
defer mem_arena.deinit();
|
||||
const mem_allocator = mem_arena.allocator();
|
||||
|
||||
// Initialize the heap
|
||||
// Initialize a min heap
|
||||
const PQlt = std.PriorityQueue(i32, void, lessThan);
|
||||
var min_heap = PQlt.init(std.heap.page_allocator, {});
|
||||
defer min_heap.deinit();
|
||||
// Initialize a max heap
|
||||
const PQgt = std.PriorityQueue(i32, void, greaterThan);
|
||||
var max_heap = PQgt.init(std.heap.page_allocator, {});
|
||||
defer max_heap.deinit();
|
||||
|
||||
std.debug.print("\nThe following example uses a max heap", .{});
|
||||
|
||||
// Push an element onto the heap
|
||||
try testPush(i32, mem_allocator, &max_heap, 1);
|
||||
try testPush(i32, mem_allocator, &max_heap, 3);
|
||||
try testPush(i32, mem_allocator, &max_heap, 2);
|
||||
try testPush(i32, mem_allocator, &max_heap, 5);
|
||||
try testPush(i32, mem_allocator, &max_heap, 4);
|
||||
|
||||
// Get the top element of the heap
|
||||
var peek = max_heap.peek().?;
|
||||
std.debug.print("\nHeap top = {}\n", .{peek});
|
||||
|
||||
// Pop the top element from the heap
|
||||
try testPop(i32, mem_allocator, &max_heap);
|
||||
try testPop(i32, mem_allocator, &max_heap);
|
||||
try testPop(i32, mem_allocator, &max_heap);
|
||||
try testPop(i32, mem_allocator, &max_heap);
|
||||
try testPop(i32, mem_allocator, &max_heap);
|
||||
|
||||
// Get the heap size
|
||||
var size = max_heap.len;
|
||||
std.debug.print("\nNumber of heap elements = {}\n", .{size});
|
||||
|
||||
// Check whether the heap is empty
|
||||
var is_empty = if (max_heap.len == 0) true else false;
|
||||
std.debug.print("\nIs the heap empty? {}\n", .{is_empty});
|
||||
|
||||
// Build a heap from an input list
|
||||
try min_heap.addSlice(&[_]i32{ 1, 3, 2, 5, 4 });
|
||||
std.debug.print("\nAfter building a min heap from the input list\n", .{});
|
||||
try inc.PrintUtil.printHeap(i32, mem_allocator, min_heap);
|
||||
|
||||
_ = try std.io.getStdIn().reader().readByte();
|
||||
}
|
||||
@@ -1,186 +0,0 @@
|
||||
// File: my_heap.zig
|
||||
// Created Time: 2023-01-14
|
||||
// Author: codingonion (coderonion@gmail.com)
|
||||
|
||||
const std = @import("std");
|
||||
const inc = @import("include");
|
||||
|
||||
// Simple heap implementation
|
||||
pub fn MaxHeap(comptime T: type) type {
|
||||
return struct {
|
||||
const Self = @This();
|
||||
|
||||
max_heap: ?std.ArrayList(T) = null, // Use a dynamic list so that capacity growth is handled automatically
|
||||
|
||||
// Initialize the heap from the input list
|
||||
pub fn init(self: *Self, allocator: std.mem.Allocator, nums: []const T) !void {
|
||||
if (self.max_heap != null) return;
|
||||
self.max_heap = std.ArrayList(T).init(allocator);
|
||||
// Place the list elements in the heap without changing their order
|
||||
try self.max_heap.?.appendSlice(nums);
|
||||
// Sift down from every non-leaf node
|
||||
var i: usize = parent(self.size() - 1) + 1;
|
||||
while (i > 0) : (i -= 1) {
|
||||
try self.siftDown(i - 1);
|
||||
}
|
||||
}
|
||||
|
||||
// Deinitialize and release the memory
|
||||
pub fn deinit(self: *Self) void {
|
||||
if (self.max_heap != null) self.max_heap.?.deinit();
|
||||
}
|
||||
|
||||
// Get the left child index
|
||||
fn left(i: usize) usize {
|
||||
return 2 * i + 1;
|
||||
}
|
||||
|
||||
// Get the right child index
|
||||
fn right(i: usize) usize {
|
||||
return 2 * i + 2;
|
||||
}
|
||||
|
||||
// Get the parent index
|
||||
fn parent(i: usize) usize {
|
||||
// return (i - 1) / 2; // Floor division
|
||||
return @divFloor(i - 1, 2);
|
||||
}
|
||||
|
||||
// Swap elements
|
||||
fn swap(self: *Self, i: usize, j: usize) !void {
|
||||
var tmp = self.max_heap.?.items[i];
|
||||
try self.max_heap.?.replaceRange(i, 1, &[_]T{self.max_heap.?.items[j]});
|
||||
try self.max_heap.?.replaceRange(j, 1, &[_]T{tmp});
|
||||
}
|
||||
|
||||
// Get the heap size
|
||||
pub fn size(self: *Self) usize {
|
||||
return self.max_heap.?.items.len;
|
||||
}
|
||||
|
||||
// Check whether the heap is empty
|
||||
pub fn isEmpty(self: *Self) bool {
|
||||
return self.size() == 0;
|
||||
}
|
||||
|
||||
// Access the top element of the heap
|
||||
pub fn peek(self: *Self) T {
|
||||
return self.max_heap.?.items[0];
|
||||
}
|
||||
|
||||
// Push an element onto the heap
|
||||
pub fn push(self: *Self, val: T) !void {
|
||||
// Add a node
|
||||
try self.max_heap.?.append(val);
|
||||
// Sift up
|
||||
try self.siftUp(self.size() - 1);
|
||||
}
|
||||
|
||||
// Sift up starting from node i
|
||||
fn siftUp(self: *Self, i_: usize) !void {
|
||||
var i = i_;
|
||||
while (true) {
|
||||
// Get the parent of node i
|
||||
var p = parent(i);
|
||||
// Stop sifting when the root has been passed or the node needs no repair
|
||||
if (p < 0 or self.max_heap.?.items[i] <= self.max_heap.?.items[p]) break;
|
||||
// Swap the two nodes
|
||||
try self.swap(i, p);
|
||||
// Continue sifting up
|
||||
i = p;
|
||||
}
|
||||
}
|
||||
|
||||
// Pop an element from the heap
|
||||
pub fn pop(self: *Self) !T {
|
||||
// Check for an empty heap
|
||||
if (self.isEmpty()) unreachable;
|
||||
// Swap the root with the rightmost leaf on the last level (swap the first and last elements)
|
||||
try self.swap(0, self.size() - 1);
|
||||
// Remove a node
|
||||
var val = self.max_heap.?.pop();
|
||||
// Sift down
|
||||
try self.siftDown(0);
|
||||
// Return the top element of the heap
|
||||
return val;
|
||||
}
|
||||
|
||||
// Sift down starting from node i
|
||||
fn siftDown(self: *Self, i_: usize) !void {
|
||||
var i = i_;
|
||||
while (true) {
|
||||
// Find the node with the largest value among i, l, and r, and store its index in ma
|
||||
var l = left(i);
|
||||
var r = right(i);
|
||||
var ma = i;
|
||||
if (l < self.size() and self.max_heap.?.items[l] > self.max_heap.?.items[ma]) ma = l;
|
||||
if (r < self.size() and self.max_heap.?.items[r] > self.max_heap.?.items[ma]) ma = r;
|
||||
// Stop if node i is largest or both child indices l and r are out of bounds
|
||||
if (ma == i) break;
|
||||
// Swap the two nodes
|
||||
try self.swap(i, ma);
|
||||
// Continue sifting down
|
||||
i = ma;
|
||||
}
|
||||
}
|
||||
|
||||
fn lessThan(context: void, a: T, b: T) std.math.Order {
|
||||
_ = context;
|
||||
return std.math.order(a, b);
|
||||
}
|
||||
|
||||
fn greaterThan(context: void, a: T, b: T) std.math.Order {
|
||||
return lessThan(context, a, b).invert();
|
||||
}
|
||||
|
||||
// Print the heap (binary tree)
|
||||
pub fn print(self: *Self, mem_allocator: std.mem.Allocator) !void {
|
||||
const PQgt = std.PriorityQueue(T, void, greaterThan);
|
||||
var queue = PQgt.init(std.heap.page_allocator, {});
|
||||
defer queue.deinit();
|
||||
try queue.addSlice(self.max_heap.?.items);
|
||||
try inc.PrintUtil.printHeap(T, mem_allocator, queue);
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
// Driver code
|
||||
pub fn main() !void {
|
||||
// Initialize the allocator
|
||||
var mem_arena = std.heap.ArenaAllocator.init(std.heap.page_allocator);
|
||||
defer mem_arena.deinit();
|
||||
const mem_allocator = mem_arena.allocator();
|
||||
|
||||
// Initialize a max heap
|
||||
var max_heap = MaxHeap(i32){};
|
||||
try max_heap.init(std.heap.page_allocator, &[_]i32{ 9, 8, 6, 6, 7, 5, 2, 1, 4, 3, 6, 2 });
|
||||
defer max_heap.deinit();
|
||||
std.debug.print("\nAfter building the heap from the input list\n", .{});
|
||||
try max_heap.print(mem_allocator);
|
||||
|
||||
// Get the top element of the heap
|
||||
var peek = max_heap.peek();
|
||||
std.debug.print("\nHeap top = {}\n", .{peek});
|
||||
|
||||
// Push an element onto the heap
|
||||
const val = 7;
|
||||
try max_heap.push(val);
|
||||
std.debug.print("\nAfter pushing {} onto the heap\n", .{val});
|
||||
try max_heap.print(mem_allocator);
|
||||
|
||||
// Pop the top element from the heap
|
||||
peek = try max_heap.pop();
|
||||
std.debug.print("\nAfter popping the top element {}\n", .{peek});
|
||||
try max_heap.print(mem_allocator);
|
||||
|
||||
// Get the heap size
|
||||
var size = max_heap.size();
|
||||
std.debug.print("\nNumber of heap elements: {}", .{size});
|
||||
|
||||
// Check whether the heap is empty
|
||||
var is_empty = max_heap.isEmpty();
|
||||
std.debug.print("\nIs the heap empty? {}\n", .{is_empty});
|
||||
|
||||
_ = try std.io.getStdIn().reader().readByte();
|
||||
}
|
||||
|
||||
@@ -1,64 +0,0 @@
|
||||
// File: binary_search.zig
|
||||
// Created Time: 2023-01-15
|
||||
// Author: codingonion (coderonion@gmail.com)
|
||||
|
||||
const std = @import("std");
|
||||
const inc = @import("include");
|
||||
|
||||
// Binary search (closed interval)
|
||||
fn binarySearch(comptime T: type, nums: std.ArrayList(T), target: T) T {
|
||||
// Initialize the closed interval [0, n-1], with i and j pointing to the first and last elements
|
||||
var i: usize = 0;
|
||||
var j: usize = nums.items.len - 1;
|
||||
// Loop until the search interval is empty (when i > j)
|
||||
while (i <= j) {
|
||||
var m = i + (j - i) / 2; // Calculate the midpoint index m
|
||||
if (nums.items[m] < target) { // In this case, target must be in [m+1, j] if it exists
|
||||
i = m + 1;
|
||||
} else if (nums.items[m] > target) { // In this case, target must be in [i, m-1] if it exists
|
||||
j = m - 1;
|
||||
} else { // The target element was found; return its index
|
||||
return @intCast(m);
|
||||
}
|
||||
}
|
||||
// The target element was not found; return -1
|
||||
return -1;
|
||||
}
|
||||
|
||||
// Binary search (left-closed, right-open interval)
|
||||
fn binarySearchLCRO(comptime T: type, nums: std.ArrayList(T), target: T) T {
|
||||
// Initialize the left-closed, right-open interval [0, n), with i at the first element and j one past the last
|
||||
var i: usize = 0;
|
||||
var j: usize = nums.items.len;
|
||||
// Search the half-open interval; it is empty when i = j
|
||||
while (i <= j) {
|
||||
var m = i + (j - i) / 2; // Calculate the midpoint index m
|
||||
if (nums.items[m] < target) { // In this case, target must be in [m+1, j) if it exists
|
||||
i = m + 1;
|
||||
} else if (nums.items[m] > target) { // In this case, target must be in [i, m) if it exists
|
||||
j = m;
|
||||
} else { // The target element was found; return its index
|
||||
return @intCast(m);
|
||||
}
|
||||
}
|
||||
// The target element was not found; return -1
|
||||
return -1;
|
||||
}
|
||||
|
||||
// Driver code
|
||||
pub fn main() !void {
|
||||
var target: i32 = 6;
|
||||
var nums = std.ArrayList(i32).init(std.heap.page_allocator);
|
||||
defer nums.deinit();
|
||||
try nums.appendSlice(&[_]i32{ 1, 3, 6, 8, 12, 15, 23, 26, 31, 35 });
|
||||
|
||||
// Binary search (closed interval)
|
||||
var index = binarySearch(i32, nums, target);
|
||||
std.debug.print("Index of target element 6 = {}\n", .{index});
|
||||
|
||||
// Binary search (left-closed, right-open interval)
|
||||
index = binarySearchLCRO(i32, nums, target);
|
||||
std.debug.print("Index of target element 6 = {}\n", .{index});
|
||||
|
||||
_ = try std.io.getStdIn().reader().readByte();
|
||||
}
|
||||
@@ -1,57 +0,0 @@
|
||||
// File: hashing_search.zig
|
||||
// Created Time: 2023-01-15
|
||||
// Author: codingonion (coderonion@gmail.com)
|
||||
|
||||
const std = @import("std");
|
||||
const inc = @import("include");
|
||||
|
||||
// Hash-based search (array)
|
||||
fn hashingSearchArray(comptime T: type, map: std.AutoHashMap(T, T), target: T) T {
|
||||
// Hash table key: target element; value: index
|
||||
// Return -1 if the hash table does not contain this key
|
||||
if (map.getKey(target) == null) return -1;
|
||||
return map.get(target).?;
|
||||
}
|
||||
|
||||
// Hash-based search (linked list)
|
||||
fn hashingSearchLinkedList(comptime T: type, map: std.AutoHashMap(T, *inc.ListNode(T)), target: T) ?*inc.ListNode(T) {
|
||||
// Hash table key: target node value; value: node object
|
||||
// If the hash table does not contain this key, return null
|
||||
if (map.getKey(target) == null) return null;
|
||||
return map.get(target);
|
||||
}
|
||||
|
||||
// Driver code
|
||||
pub fn main() !void {
|
||||
var target: i32 = 3;
|
||||
|
||||
// Hash-based search (array)
|
||||
var nums = [_]i32{ 1, 5, 3, 2, 4, 7, 5, 9, 10, 8 };
|
||||
// Initialize the hash table
|
||||
var map = std.AutoHashMap(i32, i32).init(std.heap.page_allocator);
|
||||
defer map.deinit();
|
||||
for (nums, 0..) |num, i| {
|
||||
try map.put(num, @as(i32, @intCast(i))); // key: element; value: index
|
||||
}
|
||||
var index = hashingSearchArray(i32, map, target);
|
||||
std.debug.print("Index of target element 3 = {}\n", .{index});
|
||||
|
||||
// Hash-based search (linked list)
|
||||
var mem_arena = std.heap.ArenaAllocator.init(std.heap.page_allocator);
|
||||
defer mem_arena.deinit();
|
||||
const mem_allocator = mem_arena.allocator();
|
||||
var head = try inc.ListUtil.arrToLinkedList(i32, mem_allocator, &nums);
|
||||
// Initialize the hash table
|
||||
var map1 = std.AutoHashMap(i32, *inc.ListNode(i32)).init(std.heap.page_allocator);
|
||||
defer map1.deinit();
|
||||
while (head != null) {
|
||||
try map1.put(head.?.val, head.?);
|
||||
head = head.?.next;
|
||||
}
|
||||
var node = hashingSearchLinkedList(i32, map1, target);
|
||||
std.debug.print("The node object corresponding to target value 3 is ", .{});
|
||||
try inc.PrintUtil.printLinkedList(i32, node);
|
||||
|
||||
_ = try std.io.getStdIn().reader().readByte();
|
||||
}
|
||||
|
||||
@@ -1,54 +0,0 @@
|
||||
// File: linear_search.zig
|
||||
// Created Time: 2023-01-13
|
||||
// Author: codingonion (coderonion@gmail.com)
|
||||
|
||||
const std = @import("std");
|
||||
const inc = @import("include");
|
||||
|
||||
// Linear search (array)
|
||||
fn linearSearchArray(comptime T: type, nums: std.ArrayList(T), target: T) T {
|
||||
// Traverse the array
|
||||
for (nums.items, 0..) |num, i| {
|
||||
// If the target element is found, return its index
|
||||
if (num == target) {
|
||||
return @intCast(i);
|
||||
}
|
||||
}
|
||||
// The target element was not found; return -1
|
||||
return -1;
|
||||
}
|
||||
|
||||
// Linear search (linked list)
|
||||
pub fn linearSearchLinkedList(comptime T: type, node: ?*inc.ListNode(T), target: T) ?*inc.ListNode(T) {
|
||||
var head = node;
|
||||
// Traverse the linked list
|
||||
while (head != null) {
|
||||
// The target node was found; return it
|
||||
if (head.?.val == target) return head;
|
||||
head = head.?.next;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
// Driver code
|
||||
pub fn main() !void {
|
||||
var target: i32 = 3;
|
||||
|
||||
// Perform linear search on the array
|
||||
var nums = std.ArrayList(i32).init(std.heap.page_allocator);
|
||||
defer nums.deinit();
|
||||
try nums.appendSlice(&[_]i32{ 1, 5, 3, 2, 4, 7, 5, 9, 10, 8 });
|
||||
var index = linearSearchArray(i32, nums, target);
|
||||
std.debug.print("Index of target element 3 = {}\n", .{index});
|
||||
|
||||
// Perform linear search on the linked list
|
||||
var mem_arena = std.heap.ArenaAllocator.init(std.heap.page_allocator);
|
||||
defer mem_arena.deinit();
|
||||
const mem_allocator = mem_arena.allocator();
|
||||
var head = try inc.ListUtil.listToLinkedList(i32, mem_allocator, nums);
|
||||
var node = linearSearchLinkedList(i32, head, target);
|
||||
std.debug.print("The node object corresponding to target value 3 is ", .{});
|
||||
try inc.PrintUtil.printLinkedList(i32, node);
|
||||
|
||||
_ = try std.io.getStdIn().reader().readByte();
|
||||
}
|
||||
@@ -1,58 +0,0 @@
|
||||
// File: two_sum.zig
|
||||
// Created Time: 2023-01-07
|
||||
// Author: codingonion (coderonion@gmail.com)
|
||||
|
||||
const std = @import("std");
|
||||
const inc = @import("include");
|
||||
|
||||
// Method 1: brute-force enumeration
|
||||
pub fn twoSumBruteForce(nums: []i32, target: i32) ?[2]i32 {
|
||||
var size: usize = nums.len;
|
||||
var i: usize = 0;
|
||||
// Two nested loops give a time complexity of O(n^2)
|
||||
while (i < size - 1) : (i += 1) {
|
||||
var j = i + 1;
|
||||
while (j < size) : (j += 1) {
|
||||
if (nums[i] + nums[j] == target) {
|
||||
return [_]i32{@intCast(i), @intCast(j)};
|
||||
}
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
// Method 2: auxiliary hash table
|
||||
pub fn twoSumHashTable(nums: []i32, target: i32) !?[2]i32 {
|
||||
var size: usize = nums.len;
|
||||
// The auxiliary hash table uses O(n) space
|
||||
var dic = std.AutoHashMap(i32, i32).init(std.heap.page_allocator);
|
||||
defer dic.deinit();
|
||||
var i: usize = 0;
|
||||
// A single loop gives a time complexity of O(n)
|
||||
while (i < size) : (i += 1) {
|
||||
if (dic.contains(target - nums[i])) {
|
||||
return [_]i32{dic.get(target - nums[i]).?, @intCast(i)};
|
||||
}
|
||||
try dic.put(nums[i], @intCast(i));
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
|
||||
pub fn main() !void {
|
||||
// ======= Test case =======
|
||||
var nums = [_]i32{ 2, 7, 11, 15 };
|
||||
var target: i32 = 9;
|
||||
|
||||
// ====== Driver code ======
|
||||
// Method 1
|
||||
var res = twoSumBruteForce(&nums, target).?;
|
||||
std.debug.print("Method 1: res = ", .{});
|
||||
inc.PrintUtil.printArray(i32, &res);
|
||||
// Method 2
|
||||
res = (try twoSumHashTable(&nums, target)).?;
|
||||
std.debug.print("\nMethod 2 res = ", .{});
|
||||
inc.PrintUtil.printArray(i32, &res);
|
||||
|
||||
_ = try std.io.getStdIn().reader().readByte();
|
||||
}
|
||||
@@ -1,61 +0,0 @@
|
||||
// File: bubble_sort.zig
|
||||
// Created Time: 2023-01-08
|
||||
// Author: codingonion (coderonion@gmail.com)
|
||||
|
||||
const std = @import("std");
|
||||
const inc = @import("include");
|
||||
|
||||
// Bubble sort
|
||||
fn bubbleSort(nums: []i32) void {
|
||||
// Outer loop: the unsorted range is [0, i]
|
||||
var i: usize = nums.len - 1;
|
||||
while (i > 0) : (i -= 1) {
|
||||
var j: usize = 0;
|
||||
// Inner loop: move the largest element in the unsorted range [0, i] to its right end through swaps
|
||||
while (j < i) : (j += 1) {
|
||||
if (nums[j] > nums[j + 1]) {
|
||||
// Swap nums[j] and nums[j + 1]
|
||||
var tmp = nums[j];
|
||||
nums[j] = nums[j + 1];
|
||||
nums[j + 1] = tmp;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Bubble sort (flag optimization)
|
||||
fn bubbleSortWithFlag(nums: []i32) void {
|
||||
// Outer loop: the unsorted range is [0, i]
|
||||
var i: usize = nums.len - 1;
|
||||
while (i > 0) : (i -= 1) {
|
||||
var flag = false; // Initialize the flag
|
||||
var j: usize = 0;
|
||||
// Inner loop: move the largest element in the unsorted range [0, i] to its right end through swaps
|
||||
while (j < i) : (j += 1) {
|
||||
if (nums[j] > nums[j + 1]) {
|
||||
// Swap nums[j] and nums[j + 1]
|
||||
var tmp = nums[j];
|
||||
nums[j] = nums[j + 1];
|
||||
nums[j + 1] = tmp;
|
||||
flag = true;
|
||||
}
|
||||
}
|
||||
if (!flag) break; // Exit immediately if this pass made no swaps
|
||||
}
|
||||
}
|
||||
|
||||
// Driver code
|
||||
pub fn main() !void {
|
||||
var nums = [_]i32{ 4, 1, 3, 1, 5, 2 };
|
||||
bubbleSort(&nums);
|
||||
std.debug.print("After bubble sort, nums = ", .{});
|
||||
inc.PrintUtil.printArray(i32, &nums);
|
||||
|
||||
var nums1 = [_]i32{ 4, 1, 3, 1, 5, 2 };
|
||||
bubbleSortWithFlag(&nums1);
|
||||
std.debug.print("\nAfter bubble sort, nums1 = ", .{});
|
||||
inc.PrintUtil.printArray(i32, &nums1);
|
||||
|
||||
_ = try std.io.getStdIn().reader().readByte();
|
||||
}
|
||||
|
||||
@@ -1,31 +0,0 @@
|
||||
// File: insertion_sort.zig
|
||||
// Created Time: 2023-01-08
|
||||
// Author: codingonion (coderonion@gmail.com)
|
||||
|
||||
const std = @import("std");
|
||||
const inc = @import("include");
|
||||
|
||||
// Insertion sort
|
||||
fn insertionSort(nums: []i32) void {
|
||||
// Outer loop: the sorted range is [0, i-1]
|
||||
var i: usize = 1;
|
||||
while (i < nums.len) : (i += 1) {
|
||||
var base = nums[i];
|
||||
var j: usize = i;
|
||||
// Inner loop: insert base at the correct position in the sorted range [0, i-1]
|
||||
while (j >= 1 and nums[j - 1] > base) : (j -= 1) {
|
||||
nums[j] = nums[j - 1]; // Move nums[j - 1] one position to the right
|
||||
}
|
||||
nums[j] = base; // Place base at the correct position
|
||||
}
|
||||
}
|
||||
|
||||
// Driver code
|
||||
pub fn main() !void {
|
||||
var nums = [_]i32{ 4, 1, 3, 1, 5, 2 };
|
||||
insertionSort(&nums);
|
||||
std.debug.print("After insertion sort, nums = ", .{});
|
||||
inc.PrintUtil.printArray(i32, &nums);
|
||||
|
||||
_ = try std.io.getStdIn().reader().readByte();
|
||||
}
|
||||
@@ -1,67 +0,0 @@
|
||||
// File: merge_sort.zig
|
||||
// Created Time: 2023-01-15
|
||||
// Author: codingonion (coderonion@gmail.com)
|
||||
|
||||
const std = @import("std");
|
||||
const inc = @import("include");
|
||||
|
||||
// Merge the left and right subarrays
|
||||
// Left subarray range: [left, mid]
|
||||
// Right subarray range: [mid + 1, right]
|
||||
fn merge(nums: []i32, left: usize, mid: usize, right: usize) !void {
|
||||
// Initialize the auxiliary array
|
||||
var mem_arena = std.heap.ArenaAllocator.init(std.heap.page_allocator);
|
||||
defer mem_arena.deinit();
|
||||
const mem_allocator = mem_arena.allocator();
|
||||
var tmp = try mem_allocator.alloc(i32, right + 1 - left);
|
||||
std.mem.copy(i32, tmp, nums[left..right+1]);
|
||||
// Start and end indices of the left subarray in tmp
|
||||
var leftStart = left - left;
|
||||
var leftEnd = mid - left;
|
||||
// Start and end indices of the right subarray in tmp
|
||||
var rightStart = mid + 1 - left;
|
||||
var rightEnd = right - left;
|
||||
// i and j point to the first elements of the left and right subarrays, respectively
|
||||
var i = leftStart;
|
||||
var j = rightStart;
|
||||
// Merge the left and right subarrays by overwriting the original array nums
|
||||
var k = left;
|
||||
while (k <= right) : (k += 1) {
|
||||
// If the left subarray has been exhausted, take an element from the right subarray and increment j
|
||||
if (i > leftEnd) {
|
||||
nums[k] = tmp[j];
|
||||
j += 1;
|
||||
// Otherwise, if the right subarray is exhausted or the left element is no greater than the right element, take the left element and increment i
|
||||
} else if (j > rightEnd or tmp[i] <= tmp[j]) {
|
||||
nums[k] = tmp[i];
|
||||
i += 1;
|
||||
// Otherwise, both subarrays still have elements and the left element is larger, so take the right element and increment j
|
||||
} else {
|
||||
nums[k] = tmp[j];
|
||||
j += 1;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Merge sort
|
||||
fn mergeSort(nums: []i32, left: usize, right: usize) !void {
|
||||
// Base case
|
||||
if (left >= right) return; // Stop recursing when the subarray has at most one element
|
||||
// Divide phase
|
||||
var mid = left + (right - left) / 2; // Calculate the midpoint
|
||||
try mergeSort(nums, left, mid); // Recurse on the left subarray
|
||||
try mergeSort(nums, mid + 1, right); // Recurse on the right subarray
|
||||
// Merge phase
|
||||
try merge(nums, left, mid, right);
|
||||
}
|
||||
|
||||
// Driver code
|
||||
pub fn main() !void {
|
||||
// Merge sort
|
||||
var nums = [_]i32{ 7, 3, 2, 6, 0, 1, 5, 4 };
|
||||
try mergeSort(&nums, 0, nums.len - 1);
|
||||
std.debug.print("After merge sort, nums = ", .{});
|
||||
inc.PrintUtil.printArray(i32, &nums);
|
||||
|
||||
_ = try std.io.getStdIn().reader().readByte();
|
||||
}
|
||||
@@ -1,162 +0,0 @@
|
||||
// File: quick_sort.zig
|
||||
// Created Time: 2023-01-15
|
||||
// Author: codingonion (coderonion@gmail.com)
|
||||
|
||||
const std = @import("std");
|
||||
const inc = @import("include");
|
||||
|
||||
// Quick sort implementation
|
||||
const QuickSort = struct {
|
||||
|
||||
// Swap the elements
|
||||
pub fn swap(nums: []i32, i: usize, j: usize) void {
|
||||
var tmp = nums[i];
|
||||
nums[i] = nums[j];
|
||||
nums[j] = tmp;
|
||||
}
|
||||
|
||||
// Two-pointer partitioning
|
||||
pub fn partition(nums: []i32, left: usize, right: usize) usize {
|
||||
// Use nums[left] as the pivot
|
||||
var i = left;
|
||||
var j = right;
|
||||
while (i < j) {
|
||||
while (i < j and nums[j] >= nums[left]) j -= 1; // Scan from right to left for the first element smaller than the pivot
|
||||
while (i < j and nums[i] <= nums[left]) i += 1; // Scan from left to right for the first element larger than the pivot
|
||||
swap(nums, i, j); // Swap these two elements
|
||||
}
|
||||
swap(nums, i, left); // Swap the pivot into the boundary position between the two subarrays
|
||||
return i; // Return the pivot index
|
||||
}
|
||||
|
||||
// Quick sort
|
||||
pub fn quickSort(nums: []i32, left: usize, right: usize) void {
|
||||
// Stop when the current subarray has at most one element
|
||||
if (left >= right) return;
|
||||
// Two-pointer partitioning
|
||||
var pivot = partition(nums, left, right);
|
||||
// Recurse on the left and right subarrays
|
||||
quickSort(nums, left, pivot - 1);
|
||||
quickSort(nums, pivot + 1, right);
|
||||
}
|
||||
};
|
||||
|
||||
// Quick sort implementation (median-of-three pivot optimization)
|
||||
const QuickSortMedian = struct {
|
||||
|
||||
// Swap the elements
|
||||
pub fn swap(nums: []i32, i: usize, j: usize) void {
|
||||
var tmp = nums[i];
|
||||
nums[i] = nums[j];
|
||||
nums[j] = tmp;
|
||||
}
|
||||
|
||||
// Select the median of three candidate elements
|
||||
pub fn medianThree(nums: []i32, left: usize, mid: usize, right: usize) usize {
|
||||
var l = nums[left];
|
||||
var m = nums[mid];
|
||||
var r = nums[right];
|
||||
if ((l <= m && m <= r) || (r <= m && m <= l))
|
||||
return mid; // m lies between l and r
|
||||
if ((m <= l && l <= r) || (r <= l && l <= m))
|
||||
return left; // l lies between m and r
|
||||
return right;
|
||||
}
|
||||
|
||||
// Two-pointer partitioning (median of three)
|
||||
pub fn partition(nums: []i32, left: usize, right: usize) usize {
|
||||
// Select the median of three candidate elements
|
||||
var med = medianThree(nums, left, (left + right) / 2, right);
|
||||
// Swap the median into the leftmost position of the current subarray
|
||||
swap(nums, left, med);
|
||||
// Use nums[left] as the pivot
|
||||
var i = left;
|
||||
var j = right;
|
||||
while (i < j) {
|
||||
while (i < j and nums[j] >= nums[left]) j -= 1; // Scan from right to left for the first element smaller than the pivot
|
||||
while (i < j and nums[i] <= nums[left]) i += 1; // Scan from left to right for the first element larger than the pivot
|
||||
swap(nums, i, j); // Swap these two elements
|
||||
}
|
||||
swap(nums, i, left); // Swap the pivot into the boundary position between the two subarrays
|
||||
return i; // Return the pivot index
|
||||
}
|
||||
|
||||
// Quick sort
|
||||
pub fn quickSort(nums: []i32, left: usize, right: usize) void {
|
||||
// Stop when the current subarray has at most one element
|
||||
if (left >= right) return;
|
||||
// Two-pointer partitioning
|
||||
var pivot = partition(nums, left, right);
|
||||
if (pivot == 0) return;
|
||||
// Recurse on the left and right subarrays
|
||||
quickSort(nums, left, pivot - 1);
|
||||
quickSort(nums, pivot + 1, right);
|
||||
}
|
||||
};
|
||||
|
||||
// Quick sort implementation (recursion-depth optimization)
|
||||
const QuickSortTailCall = struct {
|
||||
|
||||
// Swap the elements
|
||||
pub fn swap(nums: []i32, i: usize, j: usize) void {
|
||||
var tmp = nums[i];
|
||||
nums[i] = nums[j];
|
||||
nums[j] = tmp;
|
||||
}
|
||||
|
||||
// Two-pointer partitioning
|
||||
pub fn partition(nums: []i32, left: usize, right: usize) usize {
|
||||
// Use nums[left] as the pivot
|
||||
var i = left;
|
||||
var j = right;
|
||||
while (i < j) {
|
||||
while (i < j and nums[j] >= nums[left]) j -= 1; // Scan from right to left for the first element smaller than the pivot
|
||||
while (i < j and nums[i] <= nums[left]) i += 1; // Scan from left to right for the first element larger than the pivot
|
||||
swap(nums, i, j); // Swap these two elements
|
||||
}
|
||||
swap(nums, i, left); // Swap the pivot into the boundary position between the two subarrays
|
||||
return i; // Return the pivot index
|
||||
}
|
||||
|
||||
// Quick sort (recursion depth optimization)
|
||||
pub fn quickSort(nums: []i32, left_: usize, right_: usize) void {
|
||||
var left = left_;
|
||||
var right = right_;
|
||||
// Stop when the current subarray has at most one element
|
||||
while (left < right) {
|
||||
// Perform two-pointer partitioning
|
||||
var pivot = partition(nums, left, right);
|
||||
// Apply quick sort to the shorter of the two subarrays
|
||||
if (pivot - left < right - pivot) {
|
||||
quickSort(nums, left, pivot - 1); // Recursively sort the left subarray
|
||||
left = pivot + 1; // The remaining unsorted range is [pivot + 1, right]
|
||||
} else {
|
||||
quickSort(nums, pivot + 1, right); // Recursively sort the right subarray
|
||||
right = pivot - 1; // The remaining unsorted range is [left, pivot - 1]
|
||||
}
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
// Driver code
|
||||
pub fn main() !void {
|
||||
// Quick sort
|
||||
var nums = [_]i32{ 2, 4, 1, 0, 3, 5 };
|
||||
QuickSort.quickSort(&nums, 0, nums.len - 1);
|
||||
std.debug.print("After quick sort, nums = ", .{});
|
||||
inc.PrintUtil.printArray(i32, &nums);
|
||||
|
||||
// Quick sort (median pivot optimization)
|
||||
var nums1 = [_]i32{ 2, 4, 1, 0, 3, 5 };
|
||||
QuickSortMedian.quickSort(&nums1, 0, nums1.len - 1);
|
||||
std.debug.print("\nAfter quick sort (median-of-three pivot optimization), nums1 = ", .{});
|
||||
inc.PrintUtil.printArray(i32, &nums1);
|
||||
|
||||
// Quick sort (recursion depth optimization)
|
||||
var nums2 = [_]i32{ 2, 4, 1, 0, 3, 5 };
|
||||
QuickSortTailCall.quickSort(&nums2, 0, nums2.len - 1);
|
||||
std.debug.print("\nAfter quick sort (recursion-depth optimization), nums2 = ", .{});
|
||||
inc.PrintUtil.printArray(i32, &nums2);
|
||||
|
||||
_ = try std.io.getStdIn().reader().readByte();
|
||||
}
|
||||
@@ -1,77 +0,0 @@
|
||||
// File: radix_sort.zig
|
||||
// Created Time: 2023-01-15
|
||||
// Author: codingonion (coderonion@gmail.com)
|
||||
|
||||
const std = @import("std");
|
||||
const inc = @import("include");
|
||||
|
||||
// Get the k-th digit of num, where exp = 10^(k-1)
|
||||
fn digit(num: i32, exp: i32) i32 {
|
||||
// Passing exp instead of k avoids repeatedly performing expensive exponentiation here
|
||||
return @mod(@divFloor(num, exp), 10);
|
||||
}
|
||||
|
||||
// Counting sort (sort nums by the k-th digit)
|
||||
fn countingSortDigit(nums: []i32, exp: i32) !void {
|
||||
// Decimal digits range from 0 to 9, so the bucket array needs length 10
|
||||
var mem_arena = std.heap.ArenaAllocator.init(std.heap.page_allocator);
|
||||
// defer mem_arena.deinit();
|
||||
const mem_allocator = mem_arena.allocator();
|
||||
var counter = try mem_allocator.alloc(usize, 10);
|
||||
@memset(counter, 0);
|
||||
var n = nums.len;
|
||||
// Count the occurrences of each digit from 0 to 9
|
||||
for (nums) |num| {
|
||||
var d: u32 = @bitCast(digit(num, exp)); // Get the kth digit of the current element and store it in d
|
||||
counter[d] += 1; // Count the occurrences of digit d
|
||||
}
|
||||
// Compute prefix sums to convert occurrence counts into array positions
|
||||
var i: usize = 1;
|
||||
while (i < 10) : (i += 1) {
|
||||
counter[i] += counter[i - 1];
|
||||
}
|
||||
// Traverse in reverse and place each element into res according to the bucket counts
|
||||
var res = try mem_allocator.alloc(i32, n);
|
||||
i = n - 1;
|
||||
while (i >= 0) : (i -= 1) {
|
||||
var d: u32 = @bitCast(digit(nums[i], exp));
|
||||
var j = counter[d] - 1; // Get the destination index j for digit d in the array
|
||||
res[j] = nums[i]; // Place the current element at index j
|
||||
counter[d] -= 1; // Decrease the count for d by 1
|
||||
if (i == 0) break;
|
||||
}
|
||||
// Overwrite the original array nums with the result
|
||||
i = 0;
|
||||
while (i < n) : (i += 1) {
|
||||
nums[i] = res[i];
|
||||
}
|
||||
}
|
||||
|
||||
// Radix sort
|
||||
fn radixSort(nums: []i32) !void {
|
||||
// Get the largest array element to determine the maximum number of digits
|
||||
var m: i32 = std.math.minInt(i32);
|
||||
for (nums) |num| {
|
||||
if (num > m) m = num;
|
||||
}
|
||||
// Process digits from least significant to most significant
|
||||
var exp: i32 = 1;
|
||||
while (exp <= m) : (exp *= 10) {
|
||||
// Apply counting sort to the k-th digit of the array elements
|
||||
// k = 1 -> exp = 1
|
||||
// k = 2 -> exp = 10
|
||||
// That is, exp = 10^(k-1)
|
||||
try countingSortDigit(nums, exp);
|
||||
}
|
||||
}
|
||||
|
||||
// Driver code
|
||||
pub fn main() !void {
|
||||
// Radix sort
|
||||
var nums = [_]i32{ 23, 12, 3, 4, 788, 192 };
|
||||
try radixSort(&nums);
|
||||
std.debug.print("After radix sort, nums = ", .{});
|
||||
inc.PrintUtil.printArray(i32, &nums);
|
||||
|
||||
_ = try std.io.getStdIn().reader().readByte();
|
||||
}
|
||||
@@ -1,140 +0,0 @@
|
||||
// File: array_queue.zig
|
||||
// Created Time: 2023-01-15
|
||||
// Author: codingonion (coderonion@gmail.com)
|
||||
|
||||
const std = @import("std");
|
||||
const inc = @import("include");
|
||||
|
||||
// Queue implemented with a circular array
|
||||
pub fn ArrayQueue(comptime T: type) type {
|
||||
return struct {
|
||||
const Self = @This();
|
||||
|
||||
nums: []T = undefined, // Array that stores the queue elements
|
||||
cap: usize = 0, // Queue capacity
|
||||
front: usize = 0, // Index of the front element
|
||||
queSize: usize = 0, // Current number of queue elements
|
||||
mem_arena: ?std.heap.ArenaAllocator = null,
|
||||
mem_allocator: std.mem.Allocator = undefined, // Allocator
|
||||
|
||||
// Allocate and initialize the backing array
|
||||
pub fn init(self: *Self, allocator: std.mem.Allocator, cap: usize) !void {
|
||||
if (self.mem_arena == null) {
|
||||
self.mem_arena = std.heap.ArenaAllocator.init(allocator);
|
||||
self.mem_allocator = self.mem_arena.?.allocator();
|
||||
}
|
||||
self.cap = cap;
|
||||
self.nums = try self.mem_allocator.alloc(T, self.cap);
|
||||
@memset(self.nums, @as(T, 0));
|
||||
}
|
||||
|
||||
// Deinitialize the arena and release its memory
|
||||
pub fn deinit(self: *Self) void {
|
||||
if (self.mem_arena == null) return;
|
||||
self.mem_arena.?.deinit();
|
||||
}
|
||||
|
||||
// Get the queue capacity
|
||||
pub fn capacity(self: *Self) usize {
|
||||
return self.cap;
|
||||
}
|
||||
|
||||
// Get the queue size
|
||||
pub fn size(self: *Self) usize {
|
||||
return self.queSize;
|
||||
}
|
||||
|
||||
// Check whether the queue is empty
|
||||
pub fn isEmpty(self: *Self) bool {
|
||||
return self.queSize == 0;
|
||||
}
|
||||
|
||||
// Enqueue
|
||||
pub fn push(self: *Self, num: T) !void {
|
||||
if (self.size() == self.capacity()) {
|
||||
std.debug.print("Queue is full\n", .{});
|
||||
return;
|
||||
}
|
||||
// Calculate the index immediately after the rear element
|
||||
// Use modulo to wrap rear to the beginning when it passes the end of the array
|
||||
var rear = (self.front + self.queSize) % self.capacity();
|
||||
// Append num at the rear of the queue
|
||||
self.nums[rear] = num;
|
||||
self.queSize += 1;
|
||||
}
|
||||
|
||||
// Dequeue
|
||||
pub fn pop(self: *Self) T {
|
||||
var num = self.peek();
|
||||
// Advance the front index by one, wrapping to the start of the array if necessary
|
||||
self.front = (self.front + 1) % self.capacity();
|
||||
self.queSize -= 1;
|
||||
return num;
|
||||
}
|
||||
|
||||
// Access the front element
|
||||
pub fn peek(self: *Self) T {
|
||||
if (self.isEmpty()) @panic("Queue is empty");
|
||||
return self.nums[self.front];
|
||||
}
|
||||
|
||||
// Return a copy of the queue elements as an array
|
||||
pub fn toArray(self: *Self) ![]T {
|
||||
// Copy only the occupied queue elements
|
||||
var res = try self.mem_allocator.alloc(T, self.size());
|
||||
@memset(res, @as(T, 0));
|
||||
var i: usize = 0;
|
||||
var j: usize = self.front;
|
||||
while (i < self.size()) : ({ i += 1; j += 1; }) {
|
||||
res[i] = self.nums[j % self.capacity()];
|
||||
}
|
||||
return res;
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
// Driver code
|
||||
pub fn main() !void {
|
||||
// Initialize the queue
|
||||
var capacity: usize = 10;
|
||||
var queue = ArrayQueue(i32){};
|
||||
try queue.init(std.heap.page_allocator, capacity);
|
||||
defer queue.deinit();
|
||||
|
||||
// Enqueue elements
|
||||
try queue.push(1);
|
||||
try queue.push(3);
|
||||
try queue.push(2);
|
||||
try queue.push(5);
|
||||
try queue.push(4);
|
||||
std.debug.print("Queue queue = ", .{});
|
||||
inc.PrintUtil.printArray(i32, try queue.toArray());
|
||||
|
||||
// Access the front element
|
||||
var peek = queue.peek();
|
||||
std.debug.print("\nFront element peek = {}", .{peek});
|
||||
|
||||
// Dequeue an element
|
||||
var pop = queue.pop();
|
||||
std.debug.print("\nDequeued element pop = {}; after dequeueing, queue = ", .{pop});
|
||||
inc.PrintUtil.printArray(i32, try queue.toArray());
|
||||
|
||||
// Get the queue size
|
||||
var size = queue.size();
|
||||
std.debug.print("\nQueue size = {}", .{size});
|
||||
|
||||
// Check whether the queue is empty
|
||||
var is_empty = queue.isEmpty();
|
||||
std.debug.print("\nIs the queue empty? {}", .{is_empty});
|
||||
|
||||
// Test the circular array
|
||||
var i: i32 = 0;
|
||||
while (i < 10) : (i += 1) {
|
||||
try queue.push(i);
|
||||
_ = queue.pop();
|
||||
std.debug.print("\nAfter enqueue/dequeue round {}, queue = ", .{i});
|
||||
inc.PrintUtil.printArray(i32, try queue.toArray());
|
||||
}
|
||||
|
||||
_ = try std.io.getStdIn().reader().readByte();
|
||||
}
|
||||
@@ -1,97 +0,0 @@
|
||||
// File: array_stack.zig
|
||||
// Created Time: 2023-01-08
|
||||
// Author: codingonion (coderonion@gmail.com)
|
||||
|
||||
const std = @import("std");
|
||||
const inc = @import("include");
|
||||
|
||||
// Stack implemented with an array
|
||||
pub fn ArrayStack(comptime T: type) type {
|
||||
return struct {
|
||||
const Self = @This();
|
||||
|
||||
stack: ?std.ArrayList(T) = null,
|
||||
|
||||
// Initialize the stack's ArrayList
|
||||
pub fn init(self: *Self, allocator: std.mem.Allocator) void {
|
||||
if (self.stack == null) {
|
||||
self.stack = std.ArrayList(T).init(allocator);
|
||||
}
|
||||
}
|
||||
|
||||
// Deinitialize and release the memory
|
||||
pub fn deinit(self: *Self) void {
|
||||
if (self.stack == null) return;
|
||||
self.stack.?.deinit();
|
||||
}
|
||||
|
||||
// Get the stack size
|
||||
pub fn size(self: *Self) usize {
|
||||
return self.stack.?.items.len;
|
||||
}
|
||||
|
||||
// Check whether the stack is empty
|
||||
pub fn isEmpty(self: *Self) bool {
|
||||
return self.size() == 0;
|
||||
}
|
||||
|
||||
// Access the top element
|
||||
pub fn peek(self: *Self) T {
|
||||
if (self.isEmpty()) @panic("Stack is empty");
|
||||
return self.stack.?.items[self.size() - 1];
|
||||
}
|
||||
|
||||
// Push
|
||||
pub fn push(self: *Self, num: T) !void {
|
||||
try self.stack.?.append(num);
|
||||
}
|
||||
|
||||
// Pop
|
||||
pub fn pop(self: *Self) T {
|
||||
var num = self.stack.?.pop();
|
||||
return num;
|
||||
}
|
||||
|
||||
// Return the backing ArrayList
|
||||
pub fn toList(self: *Self) std.ArrayList(T) {
|
||||
return self.stack.?;
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
// Driver code
|
||||
pub fn main() !void {
|
||||
// Initialize the stack
|
||||
var stack = ArrayStack(i32){};
|
||||
stack.init(std.heap.page_allocator);
|
||||
// Defer releasing the memory
|
||||
defer stack.deinit();
|
||||
|
||||
// Push elements onto the stack
|
||||
try stack.push(1);
|
||||
try stack.push(3);
|
||||
try stack.push(2);
|
||||
try stack.push(5);
|
||||
try stack.push(4);
|
||||
std.debug.print("Stack stack = ", .{});
|
||||
inc.PrintUtil.printList(i32, stack.toList());
|
||||
|
||||
// Access the top element
|
||||
var peek = stack.peek();
|
||||
std.debug.print("\nTop element peek = {}", .{peek});
|
||||
|
||||
// Pop an element from the stack
|
||||
var top = stack.pop();
|
||||
std.debug.print("\nPopped element top = {}; after popping, stack = ", .{top});
|
||||
inc.PrintUtil.printList(i32, stack.toList());
|
||||
|
||||
// Get the stack size
|
||||
var size = stack.size();
|
||||
std.debug.print("\nStack size = {}", .{size});
|
||||
|
||||
// Check whether the stack is empty
|
||||
var is_empty = stack.isEmpty();
|
||||
std.debug.print("\nIs the stack empty? {}", .{is_empty});
|
||||
|
||||
_ = try std.io.getStdIn().reader().readByte();
|
||||
}
|
||||
@@ -1,51 +0,0 @@
|
||||
// File: deque.zig
|
||||
// Created Time: 2023-01-15
|
||||
// Author: codingonion (coderonion@gmail.com)
|
||||
|
||||
const std = @import("std");
|
||||
const inc = @import("include");
|
||||
|
||||
// Driver code
|
||||
pub fn main() !void {
|
||||
// Initialize the deque
|
||||
const L = std.TailQueue(i32);
|
||||
var deque = L{};
|
||||
|
||||
// Enqueue elements
|
||||
var node1 = L.Node{ .data = 2 };
|
||||
var node2 = L.Node{ .data = 5 };
|
||||
var node3 = L.Node{ .data = 4 };
|
||||
var node4 = L.Node{ .data = 3 };
|
||||
var node5 = L.Node{ .data = 1 };
|
||||
deque.append(&node1); // Add to the rear
|
||||
deque.append(&node2);
|
||||
deque.append(&node3);
|
||||
deque.prepend(&node4); // Add to the front
|
||||
deque.prepend(&node5);
|
||||
std.debug.print("Deque deque = ", .{});
|
||||
inc.PrintUtil.printQueue(i32, deque);
|
||||
|
||||
// Access an element
|
||||
var peek_first = deque.first.?.data; // Front element
|
||||
std.debug.print("\nFront element peek_first = {}", .{peek_first});
|
||||
var peek_last = deque.last.?.data; // Rear element
|
||||
std.debug.print("\nRear element peek_last = {}", .{peek_last});
|
||||
|
||||
// Dequeue an element
|
||||
var pop_first = deque.popFirst().?.data; // Dequeue the front element
|
||||
std.debug.print("\nRemoved front element pop_first = {}; deque = ", .{pop_first});
|
||||
inc.PrintUtil.printQueue(i32, deque);
|
||||
var pop_last = deque.pop().?.data; // Dequeue the rear element
|
||||
std.debug.print("\nRemoved rear element pop_last = {}; deque = ", .{pop_last});
|
||||
inc.PrintUtil.printQueue(i32, deque);
|
||||
|
||||
// Get the deque size
|
||||
var size = deque.len;
|
||||
std.debug.print("\nDeque size = {}", .{size});
|
||||
|
||||
// Check whether the deque is empty
|
||||
var is_empty = if (deque.len == 0) true else false;
|
||||
std.debug.print("\nIs the deque empty? {}", .{is_empty});
|
||||
|
||||
_ = try std.io.getStdIn().reader().readByte();
|
||||
}
|
||||
@@ -1,209 +0,0 @@
|
||||
// File: linkedlist_deque.zig
|
||||
// Created Time: 2023-01-15
|
||||
// Author: codingonion (coderonion@gmail.com)
|
||||
|
||||
const std = @import("std");
|
||||
const inc = @import("include");
|
||||
|
||||
// Doubly linked list node
|
||||
pub fn ListNode(comptime T: type) type {
|
||||
return struct {
|
||||
const Self = @This();
|
||||
|
||||
val: T = undefined, // Node value
|
||||
next: ?*Self = null, // Pointer to the next node
|
||||
prev: ?*Self = null, // Pointer to the previous node
|
||||
|
||||
// Initialize a list node with the specified value
|
||||
pub fn init(self: *Self, x: i32) void {
|
||||
self.val = x;
|
||||
self.next = null;
|
||||
self.prev = null;
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
// Deque implemented with a doubly linked list
|
||||
pub fn LinkedListDeque(comptime T: type) type {
|
||||
return struct {
|
||||
const Self = @This();
|
||||
|
||||
front: ?*ListNode(T) = null, // Head node front
|
||||
rear: ?*ListNode(T) = null, // Tail node rear
|
||||
que_size: usize = 0, // Deque size
|
||||
mem_arena: ?std.heap.ArenaAllocator = null,
|
||||
mem_allocator: std.mem.Allocator = undefined, // Allocator
|
||||
|
||||
// Initialize an empty deque and its arena allocator
|
||||
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.front = null;
|
||||
self.rear = null;
|
||||
self.que_size = 0;
|
||||
}
|
||||
|
||||
// Deinitialize the arena and release its memory
|
||||
pub fn deinit(self: *Self) void {
|
||||
if (self.mem_arena == null) return;
|
||||
self.mem_arena.?.deinit();
|
||||
}
|
||||
|
||||
// Get the deque size
|
||||
pub fn size(self: *Self) usize {
|
||||
return self.que_size;
|
||||
}
|
||||
|
||||
// Check whether the deque is empty
|
||||
pub fn isEmpty(self: *Self) bool {
|
||||
return self.size() == 0;
|
||||
}
|
||||
|
||||
// Enqueue operation
|
||||
pub fn push(self: *Self, num: T, is_front: bool) !void {
|
||||
var node = try self.mem_allocator.create(ListNode(T));
|
||||
node.init(num);
|
||||
// If the linked list is empty, make both front and rear point to node
|
||||
if (self.isEmpty()) {
|
||||
self.front = node;
|
||||
self.rear = node;
|
||||
// Enqueue at the front
|
||||
} else if (is_front) {
|
||||
// Add node to the head of the linked list
|
||||
self.front.?.prev = node;
|
||||
node.next = self.front;
|
||||
self.front = node; // Update the head node
|
||||
// Enqueue at the rear
|
||||
} else {
|
||||
// Add node to the tail of the linked list
|
||||
self.rear.?.next = node;
|
||||
node.prev = self.rear;
|
||||
self.rear = node; // Update the tail node
|
||||
}
|
||||
self.que_size += 1; // Update the queue size
|
||||
}
|
||||
|
||||
// Enqueue at the front
|
||||
pub fn pushFirst(self: *Self, num: T) !void {
|
||||
try self.push(num, true);
|
||||
}
|
||||
|
||||
// Enqueue at the rear
|
||||
pub fn pushLast(self: *Self, num: T) !void {
|
||||
try self.push(num, false);
|
||||
}
|
||||
|
||||
// Dequeue operation
|
||||
pub fn pop(self: *Self, is_front: bool) T {
|
||||
if (self.isEmpty()) @panic("Deque is empty");
|
||||
var val: T = undefined;
|
||||
// When the queue size is 1, the head and tail point to the same node
|
||||
if (self.que_size == 1) {
|
||||
val = self.front.?.val;
|
||||
self.front = null;
|
||||
self.rear = null;
|
||||
}
|
||||
// Dequeue from the front
|
||||
else if (is_front) {
|
||||
val = self.front.?.val; // Save the head node value
|
||||
// Remove the head node
|
||||
var fNext = self.front.?.next;
|
||||
fNext.?.prev = null;
|
||||
self.front.?.next = null;
|
||||
self.front = fNext; // Update the head node
|
||||
// Dequeue from the rear
|
||||
} else {
|
||||
val = self.rear.?.val; // Save the tail node value
|
||||
// Remove the tail node
|
||||
var rPrev = self.rear.?.prev;
|
||||
rPrev.?.next = null;
|
||||
self.rear.?.prev = null;
|
||||
self.rear = rPrev; // Update the tail node
|
||||
}
|
||||
self.que_size -= 1; // Update the queue size
|
||||
return val;
|
||||
}
|
||||
|
||||
// Dequeue from the front
|
||||
pub fn popFirst(self: *Self) T {
|
||||
return self.pop(true);
|
||||
}
|
||||
|
||||
// Dequeue from the rear
|
||||
pub fn popLast(self: *Self) T {
|
||||
return self.pop(false);
|
||||
}
|
||||
|
||||
// Access the front element
|
||||
pub fn peekFirst(self: *Self) T {
|
||||
if (self.isEmpty()) @panic("Deque is empty");
|
||||
return self.front.?.val;
|
||||
}
|
||||
|
||||
// Access the rear element
|
||||
pub fn peekLast(self: *Self) T {
|
||||
if (self.isEmpty()) @panic("Deque is empty");
|
||||
return self.rear.?.val;
|
||||
}
|
||||
|
||||
// Return an array for printing
|
||||
pub fn toArray(self: *Self) ![]T {
|
||||
var node = self.front;
|
||||
var res = try self.mem_allocator.alloc(T, self.size());
|
||||
@memset(res, @as(T, 0));
|
||||
var i: usize = 0;
|
||||
while (i < res.len) : (i += 1) {
|
||||
res[i] = node.?.val;
|
||||
node = node.?.next;
|
||||
}
|
||||
return res;
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
// Driver code
|
||||
pub fn main() !void {
|
||||
// Initialize the deque
|
||||
var deque = LinkedListDeque(i32){};
|
||||
try deque.init(std.heap.page_allocator);
|
||||
defer deque.deinit();
|
||||
try deque.pushLast(3);
|
||||
try deque.pushLast(2);
|
||||
try deque.pushLast(5);
|
||||
std.debug.print("Deque deque = ", .{});
|
||||
inc.PrintUtil.printArray(i32, try deque.toArray());
|
||||
|
||||
// Access an element
|
||||
var peek_first = deque.peekFirst();
|
||||
std.debug.print("\nFront element peek_first = {}", .{peek_first});
|
||||
var peek_last = deque.peekLast();
|
||||
std.debug.print("\nRear element peek_last = {}", .{peek_last});
|
||||
|
||||
// Enqueue elements
|
||||
try deque.pushLast(4);
|
||||
std.debug.print("\nAfter enqueuing element 4 at the rear, deque = ", .{});
|
||||
inc.PrintUtil.printArray(i32, try deque.toArray());
|
||||
try deque.pushFirst(1);
|
||||
std.debug.print("\nAfter enqueuing element 1 at the front, deque = ", .{});
|
||||
inc.PrintUtil.printArray(i32, try deque.toArray());
|
||||
|
||||
// Dequeue an element
|
||||
var pop_last = deque.popLast();
|
||||
std.debug.print("\nElement removed from the rear = {}; after removal, deque = ", .{pop_last});
|
||||
inc.PrintUtil.printArray(i32, try deque.toArray());
|
||||
var pop_first = deque.popFirst();
|
||||
std.debug.print("\nElement removed from the front = {}; after removal, deque = ", .{pop_first});
|
||||
inc.PrintUtil.printArray(i32, try deque.toArray());
|
||||
|
||||
// Get the deque size
|
||||
var size = deque.size();
|
||||
std.debug.print("\nDeque size = {}", .{size});
|
||||
|
||||
// Check whether the deque is empty
|
||||
var is_empty = deque.isEmpty();
|
||||
std.debug.print("\nIs the deque empty? {}", .{is_empty});
|
||||
|
||||
_ = try std.io.getStdIn().reader().readByte();
|
||||
}
|
||||
@@ -1,127 +0,0 @@
|
||||
// File: linkedlist_queue.zig
|
||||
// Created Time: 2023-01-15
|
||||
// Author: codingonion (coderonion@gmail.com)
|
||||
|
||||
const std = @import("std");
|
||||
const inc = @import("include");
|
||||
|
||||
// Queue implemented with a linked list
|
||||
pub fn LinkedListQueue(comptime T: type) type {
|
||||
return struct {
|
||||
const Self = @This();
|
||||
|
||||
front: ?*inc.ListNode(T) = null, // Head node front
|
||||
rear: ?*inc.ListNode(T) = null, // Tail node rear
|
||||
que_size: usize = 0, // Queue size
|
||||
mem_arena: ?std.heap.ArenaAllocator = null,
|
||||
mem_allocator: std.mem.Allocator = undefined, // Allocator
|
||||
|
||||
// Initialize an empty queue and its arena allocator
|
||||
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.front = null;
|
||||
self.rear = null;
|
||||
self.que_size = 0;
|
||||
}
|
||||
|
||||
// Deinitialize the arena and release its memory
|
||||
pub fn deinit(self: *Self) void {
|
||||
if (self.mem_arena == null) return;
|
||||
self.mem_arena.?.deinit();
|
||||
}
|
||||
|
||||
// Get the queue size
|
||||
pub fn size(self: *Self) usize {
|
||||
return self.que_size;
|
||||
}
|
||||
|
||||
// Check whether the queue is empty
|
||||
pub fn isEmpty(self: *Self) bool {
|
||||
return self.size() == 0;
|
||||
}
|
||||
|
||||
// Access the front element
|
||||
pub fn peek(self: *Self) T {
|
||||
if (self.size() == 0) @panic("Queue is empty");
|
||||
return self.front.?.val;
|
||||
}
|
||||
|
||||
// Enqueue
|
||||
pub fn push(self: *Self, num: T) !void {
|
||||
// Add num after the tail node
|
||||
var node = try self.mem_allocator.create(inc.ListNode(T));
|
||||
node.init(num);
|
||||
// If the queue is empty, make both the head and tail point to this node
|
||||
if (self.front == null) {
|
||||
self.front = node;
|
||||
self.rear = node;
|
||||
// If the queue is not empty, add this node after the tail node
|
||||
} else {
|
||||
self.rear.?.next = node;
|
||||
self.rear = node;
|
||||
}
|
||||
self.que_size += 1;
|
||||
}
|
||||
|
||||
// Dequeue
|
||||
pub fn pop(self: *Self) T {
|
||||
var num = self.peek();
|
||||
// Remove the head node
|
||||
self.front = self.front.?.next;
|
||||
self.que_size -= 1;
|
||||
return num;
|
||||
}
|
||||
|
||||
// Copy the linked-list elements into an array
|
||||
pub fn toArray(self: *Self) ![]T {
|
||||
var node = self.front;
|
||||
var res = try self.mem_allocator.alloc(T, self.size());
|
||||
@memset(res, @as(T, 0));
|
||||
var i: usize = 0;
|
||||
while (i < res.len) : (i += 1) {
|
||||
res[i] = node.?.val;
|
||||
node = node.?.next;
|
||||
}
|
||||
return res;
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
// Driver code
|
||||
pub fn main() !void {
|
||||
// Initialize the queue
|
||||
var queue = LinkedListQueue(i32){};
|
||||
try queue.init(std.heap.page_allocator);
|
||||
defer queue.deinit();
|
||||
|
||||
// Enqueue elements
|
||||
try queue.push(1);
|
||||
try queue.push(3);
|
||||
try queue.push(2);
|
||||
try queue.push(5);
|
||||
try queue.push(4);
|
||||
std.debug.print("Queue queue = ", .{});
|
||||
inc.PrintUtil.printArray(i32, try queue.toArray());
|
||||
|
||||
// Access the front element
|
||||
var peek = queue.peek();
|
||||
std.debug.print("\nFront element peek = {}", .{peek});
|
||||
|
||||
// Dequeue an element
|
||||
var pop = queue.pop();
|
||||
std.debug.print("\nDequeued element pop = {}; after dequeueing, queue = ", .{pop});
|
||||
inc.PrintUtil.printArray(i32, try queue.toArray());
|
||||
|
||||
// Get the queue size
|
||||
var size = queue.size();
|
||||
std.debug.print("\nQueue size = {}", .{size});
|
||||
|
||||
// Check whether the queue is empty
|
||||
var is_empty = queue.isEmpty();
|
||||
std.debug.print("\nIs the queue empty? {}", .{is_empty});
|
||||
|
||||
_ = try std.io.getStdIn().reader().readByte();
|
||||
}
|
||||
@@ -1,118 +0,0 @@
|
||||
// File: linkedlist_stack.zig
|
||||
// Created Time: 2023-01-08
|
||||
// Author: codingonion (coderonion@gmail.com)
|
||||
|
||||
const std = @import("std");
|
||||
const inc = @import("include");
|
||||
|
||||
// Stack implemented with a linked list
|
||||
pub fn LinkedListStack(comptime T: type) type {
|
||||
return struct {
|
||||
const Self = @This();
|
||||
|
||||
stack_top: ?*inc.ListNode(T) = null, // Use the head node as the stack top
|
||||
stk_size: usize = 0, // Stack size
|
||||
mem_arena: ?std.heap.ArenaAllocator = null,
|
||||
mem_allocator: std.mem.Allocator = undefined, // Allocator
|
||||
|
||||
// Initialize an empty stack and its arena allocator
|
||||
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.stack_top = null;
|
||||
self.stk_size = 0;
|
||||
}
|
||||
|
||||
// Deinitialize the arena and release its memory
|
||||
pub fn deinit(self: *Self) void {
|
||||
if (self.mem_arena == null) return;
|
||||
self.mem_arena.?.deinit();
|
||||
}
|
||||
|
||||
// Get the stack size
|
||||
pub fn size(self: *Self) usize {
|
||||
return self.stk_size;
|
||||
}
|
||||
|
||||
// Check whether the stack is empty
|
||||
pub fn isEmpty(self: *Self) bool {
|
||||
return self.size() == 0;
|
||||
}
|
||||
|
||||
// Access the top element
|
||||
pub fn peek(self: *Self) T {
|
||||
if (self.size() == 0) @panic("Stack is empty");
|
||||
return self.stack_top.?.val;
|
||||
}
|
||||
|
||||
// Push
|
||||
pub fn push(self: *Self, num: T) !void {
|
||||
var node = try self.mem_allocator.create(inc.ListNode(T));
|
||||
node.init(num);
|
||||
node.next = self.stack_top;
|
||||
self.stack_top = node;
|
||||
self.stk_size += 1;
|
||||
}
|
||||
|
||||
// Pop
|
||||
pub fn pop(self: *Self) T {
|
||||
var num = self.peek();
|
||||
self.stack_top = self.stack_top.?.next;
|
||||
self.stk_size -= 1;
|
||||
return num;
|
||||
}
|
||||
|
||||
// Copy the stack elements into an array
|
||||
pub fn toArray(self: *Self) ![]T {
|
||||
var node = self.stack_top;
|
||||
var res = try self.mem_allocator.alloc(T, self.size());
|
||||
@memset(res, @as(T, 0));
|
||||
var i: usize = 0;
|
||||
while (i < res.len) : (i += 1) {
|
||||
res[res.len - i - 1] = node.?.val;
|
||||
node = node.?.next;
|
||||
}
|
||||
return res;
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
// Driver code
|
||||
pub fn main() !void {
|
||||
// Initialize the stack
|
||||
var stack = LinkedListStack(i32){};
|
||||
try stack.init(std.heap.page_allocator);
|
||||
// Defer releasing the memory
|
||||
defer stack.deinit();
|
||||
|
||||
// Push elements onto the stack
|
||||
try stack.push(1);
|
||||
try stack.push(3);
|
||||
try stack.push(2);
|
||||
try stack.push(5);
|
||||
try stack.push(4);
|
||||
std.debug.print("Stack stack = ", .{});
|
||||
inc.PrintUtil.printArray(i32, try stack.toArray());
|
||||
|
||||
// Access the top element
|
||||
var peek = stack.peek();
|
||||
std.debug.print("\nTop element peek = {}", .{peek});
|
||||
|
||||
// Pop an element from the stack
|
||||
var pop = stack.pop();
|
||||
std.debug.print("\nPopped element pop = {}; after popping, stack = ", .{pop});
|
||||
inc.PrintUtil.printArray(i32, try stack.toArray());
|
||||
|
||||
// Get the stack size
|
||||
var size = stack.size();
|
||||
std.debug.print("\nStack size = {}", .{size});
|
||||
|
||||
// Check whether the stack is empty
|
||||
var is_empty = stack.isEmpty();
|
||||
std.debug.print("\nIs the stack empty? {}", .{is_empty});
|
||||
|
||||
_ = try std.io.getStdIn().reader().readByte();
|
||||
}
|
||||
|
||||
@@ -1,46 +0,0 @@
|
||||
// File: queue.zig
|
||||
// Created Time: 2023-01-15
|
||||
// Author: codingonion (coderonion@gmail.com)
|
||||
|
||||
const std = @import("std");
|
||||
const inc = @import("include");
|
||||
|
||||
// Driver code
|
||||
pub fn main() !void {
|
||||
// Initialize the queue
|
||||
const L = std.TailQueue(i32);
|
||||
var queue = L{};
|
||||
|
||||
// Enqueue elements
|
||||
var node1 = L.Node{ .data = 1 };
|
||||
var node2 = L.Node{ .data = 3 };
|
||||
var node3 = L.Node{ .data = 2 };
|
||||
var node4 = L.Node{ .data = 5 };
|
||||
var node5 = L.Node{ .data = 4 };
|
||||
queue.append(&node1);
|
||||
queue.append(&node2);
|
||||
queue.append(&node3);
|
||||
queue.append(&node4);
|
||||
queue.append(&node5);
|
||||
std.debug.print("Queue queue = ", .{});
|
||||
inc.PrintUtil.printQueue(i32, queue);
|
||||
|
||||
// Access the front element
|
||||
var peek = queue.first.?.data;
|
||||
std.debug.print("\nFront element peek = {}", .{peek});
|
||||
|
||||
// Dequeue an element
|
||||
var pop = queue.popFirst().?.data;
|
||||
std.debug.print("\nDequeued element pop = {}; after dequeueing, queue = ", .{pop});
|
||||
inc.PrintUtil.printQueue(i32, queue);
|
||||
|
||||
// Get the queue size
|
||||
var size = queue.len;
|
||||
std.debug.print("\nQueue size = {}", .{size});
|
||||
|
||||
// Check whether the queue is empty
|
||||
var is_empty = if (queue.len == 0) true else false;
|
||||
std.debug.print("\nIs the queue empty? {}", .{is_empty});
|
||||
|
||||
_ = try std.io.getStdIn().reader().readByte();
|
||||
}
|
||||
@@ -1,43 +0,0 @@
|
||||
// File: stack.zig
|
||||
// Created Time: 2023-01-08
|
||||
// Author: codingonion (coderonion@gmail.com)
|
||||
|
||||
const std = @import("std");
|
||||
const inc = @import("include");
|
||||
|
||||
// Driver code
|
||||
pub fn main() !void {
|
||||
// Initialize the stack
|
||||
// In Zig, ArrayList can be used as a stack
|
||||
var stack = std.ArrayList(i32).init(std.heap.page_allocator);
|
||||
// Defer releasing the memory
|
||||
defer stack.deinit();
|
||||
|
||||
// Push elements onto the stack
|
||||
try stack.append(1);
|
||||
try stack.append(3);
|
||||
try stack.append(2);
|
||||
try stack.append(5);
|
||||
try stack.append(4);
|
||||
std.debug.print("Stack stack = ", .{});
|
||||
inc.PrintUtil.printList(i32, stack);
|
||||
|
||||
// Access the top element
|
||||
var peek = stack.items[stack.items.len - 1];
|
||||
std.debug.print("\nTop element peek = {}", .{peek});
|
||||
|
||||
// Pop an element from the stack
|
||||
var pop = stack.pop();
|
||||
std.debug.print("\nPopped element pop = {}; after popping, stack = ", .{pop});
|
||||
inc.PrintUtil.printList(i32, stack);
|
||||
|
||||
// Get the stack size
|
||||
var size = stack.items.len;
|
||||
std.debug.print("\nStack size = {}", .{size});
|
||||
|
||||
// Check whether the stack is empty
|
||||
var is_empty = if (stack.items.len == 0) true else false;
|
||||
std.debug.print("\nIs the stack empty? {}", .{is_empty});
|
||||
|
||||
_ = try std.io.getStdIn().reader().readByte();
|
||||
}
|
||||
@@ -1,249 +0,0 @@
|
||||
// File: avl_tree.zig
|
||||
// Created Time: 2023-01-15
|
||||
// Author: codingonion (coderonion@gmail.com)
|
||||
|
||||
const std = @import("std");
|
||||
const inc = @import("include");
|
||||
|
||||
// AVL tree
|
||||
pub fn AVLTree(comptime T: type) type {
|
||||
return struct {
|
||||
const Self = @This();
|
||||
|
||||
root: ?*inc.TreeNode(T) = null, // Root node
|
||||
mem_arena: ?std.heap.ArenaAllocator = null,
|
||||
mem_allocator: std.mem.Allocator = undefined, // Allocator
|
||||
|
||||
// Initialize the arena allocator
|
||||
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();
|
||||
}
|
||||
}
|
||||
|
||||
// Deinitialize the arena and release its memory
|
||||
pub fn deinit(self: *Self) void {
|
||||
if (self.mem_arena == null) return;
|
||||
self.mem_arena.?.deinit();
|
||||
}
|
||||
|
||||
// Get the node height
|
||||
fn height(self: *Self, node: ?*inc.TreeNode(T)) i32 {
|
||||
_ = self;
|
||||
// A null node has height -1; a leaf has height 0
|
||||
return if (node == null) -1 else node.?.height;
|
||||
}
|
||||
|
||||
// Update the node height
|
||||
fn updateHeight(self: *Self, node: ?*inc.TreeNode(T)) void {
|
||||
// The node height equals the height of its taller subtree + 1
|
||||
node.?.height = @max(self.height(node.?.left), self.height(node.?.right)) + 1;
|
||||
}
|
||||
|
||||
// Get the balance factor
|
||||
fn balanceFactor(self: *Self, node: ?*inc.TreeNode(T)) i32 {
|
||||
// A null node has balance factor 0
|
||||
if (node == null) return 0;
|
||||
// Node balance factor = left subtree height - right subtree height
|
||||
return self.height(node.?.left) - self.height(node.?.right);
|
||||
}
|
||||
|
||||
// Right rotation
|
||||
fn rightRotate(self: *Self, node: ?*inc.TreeNode(T)) ?*inc.TreeNode(T) {
|
||||
var child = node.?.left;
|
||||
var grandChild = child.?.right;
|
||||
// Rotate node to the right around child
|
||||
child.?.right = node;
|
||||
node.?.left = grandChild;
|
||||
// Update the node height
|
||||
self.updateHeight(node);
|
||||
self.updateHeight(child);
|
||||
// Return the root of the rotated subtree
|
||||
return child;
|
||||
}
|
||||
|
||||
// Left rotation
|
||||
fn leftRotate(self: *Self, node: ?*inc.TreeNode(T)) ?*inc.TreeNode(T) {
|
||||
var child = node.?.right;
|
||||
var grandChild = child.?.left;
|
||||
// Rotate node to the left around child
|
||||
child.?.left = node;
|
||||
node.?.right = grandChild;
|
||||
// Update the node height
|
||||
self.updateHeight(node);
|
||||
self.updateHeight(child);
|
||||
// Return the root of the rotated subtree
|
||||
return child;
|
||||
}
|
||||
|
||||
// Perform rotations to restore balance in this subtree
|
||||
fn rotate(self: *Self, node: ?*inc.TreeNode(T)) ?*inc.TreeNode(T) {
|
||||
// Get the balance factor of node
|
||||
var balance_factor = self.balanceFactor(node);
|
||||
// Left-heavy tree
|
||||
if (balance_factor > 1) {
|
||||
if (self.balanceFactor(node.?.left) >= 0) {
|
||||
// Rotate right
|
||||
return self.rightRotate(node);
|
||||
} else {
|
||||
// Rotate left, then right
|
||||
node.?.left = self.leftRotate(node.?.left);
|
||||
return self.rightRotate(node);
|
||||
}
|
||||
}
|
||||
// Right-heavy tree
|
||||
if (balance_factor < -1) {
|
||||
if (self.balanceFactor(node.?.right) <= 0) {
|
||||
// Rotate left
|
||||
return self.leftRotate(node);
|
||||
} else {
|
||||
// Rotate right, then left
|
||||
node.?.right = self.rightRotate(node.?.right);
|
||||
return self.leftRotate(node);
|
||||
}
|
||||
}
|
||||
// The tree is balanced; return without rotating
|
||||
return node;
|
||||
}
|
||||
|
||||
// Insert a node
|
||||
fn insert(self: *Self, val: T) !void {
|
||||
self.root = (try self.insertHelper(self.root, val)).?;
|
||||
}
|
||||
|
||||
// Insert a node recursively (helper method)
|
||||
fn insertHelper(self: *Self, node_: ?*inc.TreeNode(T), val: T) !?*inc.TreeNode(T) {
|
||||
var node = node_;
|
||||
if (node == null) {
|
||||
var tmp_node = try self.mem_allocator.create(inc.TreeNode(T));
|
||||
tmp_node.init(val);
|
||||
return tmp_node;
|
||||
}
|
||||
// 1. Find the insertion position and insert the node
|
||||
if (val < node.?.val) {
|
||||
node.?.left = try self.insertHelper(node.?.left, val);
|
||||
} else if (val > node.?.val) {
|
||||
node.?.right = try self.insertHelper(node.?.right, val);
|
||||
} else {
|
||||
return node; // Return without inserting a duplicate node
|
||||
}
|
||||
self.updateHeight(node); // Update the node height
|
||||
// 2. Perform rotations to restore balance in this subtree
|
||||
node = self.rotate(node);
|
||||
// Return the root of the subtree
|
||||
return node;
|
||||
}
|
||||
|
||||
// Remove a node
|
||||
fn remove(self: *Self, val: T) void {
|
||||
self.root = self.removeHelper(self.root, val).?;
|
||||
}
|
||||
|
||||
// Remove a node recursively (helper method)
|
||||
fn removeHelper(self: *Self, node_: ?*inc.TreeNode(T), val: T) ?*inc.TreeNode(T) {
|
||||
var node = node_;
|
||||
if (node == null) return null;
|
||||
// 1. Find and remove the node
|
||||
if (val < node.?.val) {
|
||||
node.?.left = self.removeHelper(node.?.left, val);
|
||||
} else if (val > node.?.val) {
|
||||
node.?.right = self.removeHelper(node.?.right, val);
|
||||
} else {
|
||||
if (node.?.left == null or node.?.right == null) {
|
||||
var child = if (node.?.left != null) node.?.left else node.?.right;
|
||||
// Number of children = 0: remove node and return
|
||||
if (child == null) {
|
||||
return null;
|
||||
// Number of children = 1: remove node directly
|
||||
} else {
|
||||
node = child;
|
||||
}
|
||||
} else {
|
||||
// Number of children = 2: remove the inorder successor and use its value to replace the current node value
|
||||
var temp = node.?.right;
|
||||
while (temp.?.left != null) {
|
||||
temp = temp.?.left;
|
||||
}
|
||||
node.?.right = self.removeHelper(node.?.right, temp.?.val);
|
||||
node.?.val = temp.?.val;
|
||||
}
|
||||
}
|
||||
self.updateHeight(node); // Update the node height
|
||||
// 2. Perform rotations to restore balance in this subtree
|
||||
node = self.rotate(node);
|
||||
// Return the root of the subtree
|
||||
return node;
|
||||
}
|
||||
|
||||
// Find a node
|
||||
fn search(self: *Self, val: T) ?*inc.TreeNode(T) {
|
||||
var cur = self.root;
|
||||
// Search while cur is not null
|
||||
while (cur != null) {
|
||||
// The target node lies in the right subtree of cur
|
||||
if (cur.?.val < val) {
|
||||
cur = cur.?.right;
|
||||
// The target node lies in the left subtree of cur
|
||||
} else if (cur.?.val > val) {
|
||||
cur = cur.?.left;
|
||||
// The target node was found; exit the loop
|
||||
} else {
|
||||
break;
|
||||
}
|
||||
}
|
||||
// Return the matching node, or null if no match was found
|
||||
return cur;
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
pub fn testInsert(comptime T: type, tree_: *AVLTree(T), val: T) !void {
|
||||
var tree = tree_;
|
||||
try tree.insert(val);
|
||||
std.debug.print("\nAVL tree after inserting node {}:\n", .{val});
|
||||
try inc.PrintUtil.printTree(tree.root, null, false);
|
||||
}
|
||||
|
||||
pub fn testRemove(comptime T: type, tree_: *AVLTree(T), val: T) void {
|
||||
var tree = tree_;
|
||||
tree.remove(val);
|
||||
std.debug.print("\nAVL tree after removing node {}:\n", .{val});
|
||||
try inc.PrintUtil.printTree(tree.root, null, false);
|
||||
}
|
||||
|
||||
// Driver code
|
||||
pub fn main() !void {
|
||||
// Initialize an empty AVL tree
|
||||
var avl_tree = AVLTree(i32){};
|
||||
avl_tree.init(std.heap.page_allocator);
|
||||
defer avl_tree.deinit();
|
||||
|
||||
// Insert a node
|
||||
// Observe how the AVL tree maintains balance after a node is inserted
|
||||
try testInsert(i32, &avl_tree, 1);
|
||||
try testInsert(i32, &avl_tree, 2);
|
||||
try testInsert(i32, &avl_tree, 3);
|
||||
try testInsert(i32, &avl_tree, 4);
|
||||
try testInsert(i32, &avl_tree, 5);
|
||||
try testInsert(i32, &avl_tree, 8);
|
||||
try testInsert(i32, &avl_tree, 7);
|
||||
try testInsert(i32, &avl_tree, 9);
|
||||
try testInsert(i32, &avl_tree, 10);
|
||||
try testInsert(i32, &avl_tree, 6);
|
||||
|
||||
// Insert a duplicate node
|
||||
try testInsert(i32, &avl_tree, 7);
|
||||
|
||||
// Remove a node
|
||||
// Observe how the AVL tree maintains balance after a node is removed
|
||||
testRemove(i32, &avl_tree, 8); // Remove a node with 0 children
|
||||
testRemove(i32, &avl_tree, 5); // Remove a node with 1 child
|
||||
testRemove(i32, &avl_tree, 4); // Remove a node with 2 children
|
||||
|
||||
// Find a node
|
||||
var node = avl_tree.search(7).?;
|
||||
std.debug.print("\nFound node: {any}, node value = {}\n", .{node, node.val});
|
||||
|
||||
_ = try std.io.getStdIn().reader().readByte();
|
||||
}
|
||||
@@ -1,182 +0,0 @@
|
||||
// File: binary_search_tree.zig
|
||||
// Created Time: 2023-01-15
|
||||
// Author: codingonion (coderonion@gmail.com)
|
||||
|
||||
const std = @import("std");
|
||||
const inc = @import("include");
|
||||
|
||||
// Binary search tree
|
||||
pub fn BinarySearchTree(comptime T: type) type {
|
||||
return struct {
|
||||
const Self = @This();
|
||||
|
||||
root: ?*inc.TreeNode(T) = null,
|
||||
mem_arena: ?std.heap.ArenaAllocator = null,
|
||||
mem_allocator: std.mem.Allocator = undefined, // Allocator
|
||||
|
||||
// Initialize the allocator and build the tree from the array
|
||||
pub fn init(self: *Self, allocator: std.mem.Allocator, nums: []T) !void {
|
||||
if (self.mem_arena == null) {
|
||||
self.mem_arena = std.heap.ArenaAllocator.init(allocator);
|
||||
self.mem_allocator = self.mem_arena.?.allocator();
|
||||
}
|
||||
std.mem.sort(T, nums, {}, comptime std.sort.asc(T)); // Sort the array
|
||||
self.root = try self.buildTree(nums, 0, nums.len - 1); // Build the binary search tree
|
||||
}
|
||||
|
||||
// Deinitialize the arena and release its memory
|
||||
pub fn deinit(self: *Self) void {
|
||||
if (self.mem_arena == null) return;
|
||||
self.mem_arena.?.deinit();
|
||||
}
|
||||
|
||||
// Build the binary search tree
|
||||
fn buildTree(self: *Self, nums: []T, i: usize, j: usize) !?*inc.TreeNode(T) {
|
||||
if (i > j) return null;
|
||||
// Use the middle array element as the root value
|
||||
var mid = i + (j - i) / 2;
|
||||
var node = try self.mem_allocator.create(inc.TreeNode(T));
|
||||
node.init(nums[mid]);
|
||||
// Recursively build the left and right subtrees
|
||||
if (mid >= 1) node.left = try self.buildTree(nums, i, mid - 1);
|
||||
node.right = try self.buildTree(nums, mid + 1, j);
|
||||
return node;
|
||||
}
|
||||
|
||||
// Get the root of the binary tree
|
||||
fn getRoot(self: *Self) ?*inc.TreeNode(T) {
|
||||
return self.root;
|
||||
}
|
||||
|
||||
// Find a node
|
||||
fn search(self: *Self, num: T) ?*inc.TreeNode(T) {
|
||||
var cur = self.root;
|
||||
// Search while cur is not null
|
||||
while (cur != null) {
|
||||
// The target node lies in the right subtree of cur
|
||||
if (cur.?.val < num) {
|
||||
cur = cur.?.right;
|
||||
// The target node lies in the left subtree of cur
|
||||
} else if (cur.?.val > num) {
|
||||
cur = cur.?.left;
|
||||
// The target node was found; exit the loop
|
||||
} else {
|
||||
break;
|
||||
}
|
||||
}
|
||||
// Return the matching node, or null if no match was found
|
||||
return cur;
|
||||
}
|
||||
|
||||
// Insert a node
|
||||
fn insert(self: *Self, num: T) !void {
|
||||
// If the tree is empty, allocate a root node
|
||||
if (self.root == null) {
|
||||
self.root = try self.mem_allocator.create(inc.TreeNode(T));
|
||||
return;
|
||||
}
|
||||
var cur = self.root;
|
||||
var pre: ?*inc.TreeNode(T) = null;
|
||||
// Search while cur is not null
|
||||
while (cur != null) {
|
||||
// Return immediately if a duplicate node is found
|
||||
if (cur.?.val == num) return;
|
||||
pre = cur;
|
||||
// The insertion position lies in the right subtree of cur
|
||||
if (cur.?.val < num) {
|
||||
cur = cur.?.right;
|
||||
// The insertion position lies in the left subtree of cur
|
||||
} else {
|
||||
cur = cur.?.left;
|
||||
}
|
||||
}
|
||||
// Insert a node
|
||||
var node = try self.mem_allocator.create(inc.TreeNode(T));
|
||||
node.init(num);
|
||||
if (pre.?.val < num) {
|
||||
pre.?.right = node;
|
||||
} else {
|
||||
pre.?.left = node;
|
||||
}
|
||||
}
|
||||
|
||||
// Remove a node
|
||||
fn remove(self: *Self, num: T) void {
|
||||
// Return immediately if the tree is empty
|
||||
if (self.root == null) return;
|
||||
var cur = self.root;
|
||||
var pre: ?*inc.TreeNode(T) = null;
|
||||
// Search while cur is not null
|
||||
while (cur != null) {
|
||||
// The node to remove was found; exit the loop
|
||||
if (cur.?.val == num) break;
|
||||
pre = cur;
|
||||
// The node to remove lies in the right subtree of cur
|
||||
if (cur.?.val < num) {
|
||||
cur = cur.?.right;
|
||||
// The node to remove lies in the left subtree of cur
|
||||
} else {
|
||||
cur = cur.?.left;
|
||||
}
|
||||
}
|
||||
// Return immediately if the node to remove does not exist
|
||||
if (cur == null) return;
|
||||
// Number of children = 0 or 1
|
||||
if (cur.?.left == null or cur.?.right == null) {
|
||||
// With 0 or 1 child, child is null or the existing child, respectively
|
||||
var child = if (cur.?.left != null) cur.?.left else cur.?.right;
|
||||
// Remove node cur
|
||||
if (pre.?.left == cur) {
|
||||
pre.?.left = child;
|
||||
} else {
|
||||
pre.?.right = child;
|
||||
}
|
||||
// Number of children = 2
|
||||
} else {
|
||||
// Get the inorder successor of cur
|
||||
var tmp = cur.?.right;
|
||||
while (tmp.?.left != null) {
|
||||
tmp = tmp.?.left;
|
||||
}
|
||||
var tmp_val = tmp.?.val;
|
||||
// Recursively remove node tmp
|
||||
self.remove(tmp.?.val);
|
||||
// Replace the value of cur with the value of tmp
|
||||
cur.?.val = tmp_val;
|
||||
}
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
// Driver code
|
||||
pub fn main() !void {
|
||||
// Initialize the binary tree
|
||||
var nums = [_]i32{ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15 };
|
||||
var bst = BinarySearchTree(i32){};
|
||||
try bst.init(std.heap.page_allocator, &nums);
|
||||
defer bst.deinit();
|
||||
std.debug.print("Binary tree after initialization:\n", .{});
|
||||
try inc.PrintUtil.printTree(bst.getRoot(), null, false);
|
||||
|
||||
// Find a node
|
||||
var node = bst.search(7);
|
||||
std.debug.print("\nFound node: {any}, node value = {}\n", .{node, node.?.val});
|
||||
|
||||
// Insert a node
|
||||
try bst.insert(16);
|
||||
std.debug.print("\nBinary tree after inserting node 16:\n", .{});
|
||||
try inc.PrintUtil.printTree(bst.getRoot(), null, false);
|
||||
|
||||
// Remove a node
|
||||
bst.remove(1);
|
||||
std.debug.print("\nBinary tree after removing node 1:\n", .{});
|
||||
try inc.PrintUtil.printTree(bst.getRoot(), null, false);
|
||||
bst.remove(2);
|
||||
std.debug.print("\nBinary tree after removing node 2:\n", .{});
|
||||
try inc.PrintUtil.printTree(bst.getRoot(), null, false);
|
||||
bst.remove(4);
|
||||
std.debug.print("\nBinary tree after removing node 4:\n", .{});
|
||||
try inc.PrintUtil.printTree(bst.getRoot(), null, false);
|
||||
|
||||
_ = try std.io.getStdIn().reader().readByte();
|
||||
}
|
||||
@@ -1,39 +0,0 @@
|
||||
// File: binary_tree.zig
|
||||
// Created Time: 2023-01-14
|
||||
// Author: codingonion (coderonion@gmail.com)
|
||||
|
||||
const std = @import("std");
|
||||
const inc = @import("include");
|
||||
|
||||
// Driver code
|
||||
pub fn main() !void {
|
||||
// Initialize the binary tree
|
||||
// Initialize the nodes
|
||||
var n1 = inc.TreeNode(i32){ .val = 1 };
|
||||
var n2 = inc.TreeNode(i32){ .val = 2 };
|
||||
var n3 = inc.TreeNode(i32){ .val = 3 };
|
||||
var n4 = inc.TreeNode(i32){ .val = 4 };
|
||||
var n5 = inc.TreeNode(i32){ .val = 5 };
|
||||
// Set up references (pointers) between the nodes
|
||||
n1.left = &n2;
|
||||
n1.right = &n3;
|
||||
n2.left = &n4;
|
||||
n2.right = &n5;
|
||||
std.debug.print("Initialize the binary tree\n", .{});
|
||||
try inc.PrintUtil.printTree(&n1, null, false);
|
||||
|
||||
// Insert and remove nodes
|
||||
var p = inc.TreeNode(i32){ .val = 0 };
|
||||
// Insert node p between n1 and n2
|
||||
n1.left = &p;
|
||||
p.left = &n2;
|
||||
std.debug.print("After inserting node p\n", .{});
|
||||
try inc.PrintUtil.printTree(&n1, null, false);
|
||||
// Remove a node
|
||||
n1.left = &n2;
|
||||
std.debug.print("After removing node p\n", .{});
|
||||
try inc.PrintUtil.printTree(&n1, null, false);
|
||||
|
||||
_ = try std.io.getStdIn().reader().readByte();
|
||||
}
|
||||
|
||||
@@ -1,57 +0,0 @@
|
||||
// File: binary_tree_bfs.zig
|
||||
// Created Time: 2023-01-15
|
||||
// Author: codingonion (coderonion@gmail.com)
|
||||
|
||||
const std = @import("std");
|
||||
const inc = @import("include");
|
||||
|
||||
// Level-order traversal
|
||||
fn levelOrder(comptime T: type, mem_allocator: std.mem.Allocator, root: *inc.TreeNode(T)) !std.ArrayList(T) {
|
||||
// Initialize a queue and enqueue the root
|
||||
const L = std.TailQueue(*inc.TreeNode(T));
|
||||
var queue = L{};
|
||||
var root_node = try mem_allocator.create(L.Node);
|
||||
root_node.data = root;
|
||||
queue.append(root_node);
|
||||
// Initialize a list to store the traversal sequence
|
||||
var list = std.ArrayList(T).init(std.heap.page_allocator);
|
||||
while (queue.len > 0) {
|
||||
var queue_node = queue.popFirst().?; // Dequeue from the queue
|
||||
var node = queue_node.data;
|
||||
try list.append(node.val); // Store the node value
|
||||
if (node.left != null) {
|
||||
var tmp_node = try mem_allocator.create(L.Node);
|
||||
tmp_node.data = node.left.?;
|
||||
queue.append(tmp_node); // Enqueue the left child
|
||||
}
|
||||
if (node.right != null) {
|
||||
var tmp_node = try mem_allocator.create(L.Node);
|
||||
tmp_node.data = node.right.?;
|
||||
queue.append(tmp_node); // Enqueue the right child
|
||||
}
|
||||
}
|
||||
return list;
|
||||
}
|
||||
|
||||
// Driver code
|
||||
pub fn main() !void {
|
||||
// Initialize the allocator
|
||||
var mem_arena = std.heap.ArenaAllocator.init(std.heap.page_allocator);
|
||||
defer mem_arena.deinit();
|
||||
const mem_allocator = mem_arena.allocator();
|
||||
|
||||
// Initialize the binary tree
|
||||
// Use a helper function that builds a binary tree directly from an array
|
||||
var nums = [_]i32{1, 2, 3, 4, 5, 6, 7};
|
||||
var root = try inc.TreeUtil.arrToTree(i32, mem_allocator, &nums);
|
||||
std.debug.print("Initialize the binary tree\n", .{});
|
||||
try inc.PrintUtil.printTree(root, null, false);
|
||||
|
||||
// Level-order traversal
|
||||
var list = try levelOrder(i32, mem_allocator, root.?);
|
||||
defer list.deinit();
|
||||
std.debug.print("\nNode sequence from level-order traversal = ", .{});
|
||||
inc.PrintUtil.printList(i32, list);
|
||||
|
||||
_ = try std.io.getStdIn().reader().readByte();
|
||||
}
|
||||
@@ -1,70 +0,0 @@
|
||||
// File: binary_tree_dfs.zig
|
||||
// Created Time: 2023-01-15
|
||||
// Author: codingonion (coderonion@gmail.com)
|
||||
|
||||
const std = @import("std");
|
||||
const inc = @import("include");
|
||||
|
||||
var list = std.ArrayList(i32).init(std.heap.page_allocator);
|
||||
|
||||
// Preorder traversal
|
||||
fn preOrder(comptime T: type, root: ?*inc.TreeNode(T)) !void {
|
||||
if (root == null) return;
|
||||
// Visit order: root -> left subtree -> right subtree
|
||||
try list.append(root.?.val);
|
||||
try preOrder(T, root.?.left);
|
||||
try preOrder(T, root.?.right);
|
||||
}
|
||||
|
||||
// Inorder traversal
|
||||
fn inOrder(comptime T: type, root: ?*inc.TreeNode(T)) !void {
|
||||
if (root == null) return;
|
||||
// Visit order: left subtree -> root -> right subtree
|
||||
try inOrder(T, root.?.left);
|
||||
try list.append(root.?.val);
|
||||
try inOrder(T, root.?.right);
|
||||
}
|
||||
|
||||
// Postorder traversal
|
||||
fn postOrder(comptime T: type, root: ?*inc.TreeNode(T)) !void {
|
||||
if (root == null) return;
|
||||
// Visit order: left subtree -> right subtree -> root
|
||||
try postOrder(T, root.?.left);
|
||||
try postOrder(T, root.?.right);
|
||||
try list.append(root.?.val);
|
||||
}
|
||||
|
||||
// Driver code
|
||||
pub fn main() !void {
|
||||
// Initialize the allocator
|
||||
var mem_arena = std.heap.ArenaAllocator.init(std.heap.page_allocator);
|
||||
defer mem_arena.deinit();
|
||||
const mem_allocator = mem_arena.allocator();
|
||||
|
||||
// Initialize the binary tree
|
||||
// Use a helper function that builds a binary tree directly from an array
|
||||
var nums = [_]i32{1, 2, 3, 4, 5, 6, 7};
|
||||
var root = try inc.TreeUtil.arrToTree(i32, mem_allocator, &nums);
|
||||
std.debug.print("Initialize the binary tree\n", .{});
|
||||
try inc.PrintUtil.printTree(root, null, false);
|
||||
|
||||
// Preorder traversal
|
||||
list.clearRetainingCapacity();
|
||||
try preOrder(i32, root);
|
||||
std.debug.print("\nNode sequence from preorder traversal = ", .{});
|
||||
inc.PrintUtil.printList(i32, list);
|
||||
|
||||
// Inorder traversal
|
||||
list.clearRetainingCapacity();
|
||||
try inOrder(i32, root);
|
||||
std.debug.print("\nNode sequence from inorder traversal = ", .{});
|
||||
inc.PrintUtil.printList(i32, list);
|
||||
|
||||
// Postorder traversal
|
||||
list.clearRetainingCapacity();
|
||||
try postOrder(i32, root);
|
||||
std.debug.print("\nPostorder traversal sequence = ", .{});
|
||||
inc.PrintUtil.printList(i32, list);
|
||||
|
||||
_ = try std.io.getStdIn().reader().readByte();
|
||||
}
|
||||
@@ -1,42 +0,0 @@
|
||||
// File: PrintUtil.zig
|
||||
// Created Time: 2023-01-07
|
||||
// Author: codingonion (coderonion@gmail.com)
|
||||
|
||||
const std = @import("std");
|
||||
pub const ListUtil = @import("ListNode.zig");
|
||||
pub const ListNode = ListUtil.ListNode;
|
||||
pub const TreeUtil = @import("TreeNode.zig");
|
||||
pub const TreeNode = TreeUtil.TreeNode;
|
||||
|
||||
// Print the queue
|
||||
pub fn printQueue(comptime T: type, queue: std.TailQueue(T)) void {
|
||||
var node = queue.first;
|
||||
std.debug.print("[", .{});
|
||||
var i: i32 = 0;
|
||||
while (node != null) : (i += 1) {
|
||||
var data = node.?.data;
|
||||
std.debug.print("{}{s}", .{ data, if (i == queue.len - 1) "]" else ", " });
|
||||
node = node.?.next;
|
||||
}
|
||||
}
|
||||
|
||||
// Print the hash table
|
||||
pub fn printHashMap(comptime TKey: type, comptime TValue: type, map: std.AutoHashMap(TKey, TValue)) void {
|
||||
var it = map.iterator();
|
||||
while (it.next()) |kv| {
|
||||
var key = kv.key_ptr.*;
|
||||
var value = kv.value_ptr.*;
|
||||
std.debug.print("{} -> {s}\n", .{ key, value });
|
||||
}
|
||||
}
|
||||
|
||||
// Print a heap
|
||||
pub fn printHeap(comptime T: type, mem_allocator: std.mem.Allocator, queue: anytype) !void {
|
||||
var arr = queue.items;
|
||||
var len = queue.len;
|
||||
std.debug.print("Array representation of the heap:", .{});
|
||||
printArray(T, arr[0..len]);
|
||||
std.debug.print("\nTree representation of the heap:\n", .{});
|
||||
var root = try TreeUtil.arrToTree(T, mem_allocator, arr[0..len]);
|
||||
try printTree(root, null, false);
|
||||
}
|
||||
@@ -1,7 +0,0 @@
|
||||
// File: include.zig
|
||||
// Created Time: 2023-01-07
|
||||
// Author: codingonion (coderonion@gmail.com)
|
||||
|
||||
pub const PrintUtil = @import("PrintUtil.zig");
|
||||
pub const TreeUtil = @import("TreeNode.zig");
|
||||
pub const TreeNode = TreeUtil.TreeNode;
|
||||
@@ -25,7 +25,7 @@ RUN for LANG in $LANGS; do \
|
||||
apt-get install -y dotnet-sdk-8.0 ;; \
|
||||
# その他の言語...
|
||||
*) \
|
||||
echo "警告:$LANG のインストール手順がありません" ;; \
|
||||
echo "エラー:$LANG のインストール手順がありません" >&2; exit 1 ;; \
|
||||
esac \
|
||||
done
|
||||
|
||||
|
||||
@@ -16,13 +16,6 @@ pub fn build(b: *std.Build) void {
|
||||
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",
|
||||
};
|
||||
|
||||
const test_step = b.step("test", "ユニットテストを実行する");
|
||||
@@ -41,14 +34,13 @@ fn buildChapterExeModules(
|
||||
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;
|
||||
var chapter_dir = std.fs.cwd().openDir(chapter_dir_name, .{ .iterate = true }) catch |err| @panic(@errorName(err));
|
||||
defer chapter_dir.close();
|
||||
|
||||
var it = chapter_dir.iterate();
|
||||
while (it.next() catch continue) |chapter_dir_entry| {
|
||||
while (it.next() catch |err| @panic(@errorName(err))) |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;
|
||||
const exe_mod = buildExeModuleFromChapterDirEntry(b, target, optimize, chapter_dir_name, chapter_dir_entry) catch |err| @panic(@errorName(err));
|
||||
addTestStepToExeModule(b, test_step, exe_mod, test_filters);
|
||||
}
|
||||
}
|
||||
@@ -64,30 +56,6 @@ fn buildExeModuleFromChapterDirEntry(
|
||||
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]; // xxx.zig から 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("現在実行している Zig ファイル名 = {s}\n", .{zig_file_name});
|
||||
|
||||
const exe_mod = b.createModule(.{
|
||||
.root_source_file = b.path(zig_file_path),
|
||||
.target = target,
|
||||
|
||||
@@ -1,44 +0,0 @@
|
||||
// File: climbing_stairs_backtrack.zig
|
||||
// Created Time: 2023-07-15
|
||||
// Author: codingonion (coderonion@gmail.com)
|
||||
|
||||
const std = @import("std");
|
||||
|
||||
// バックトラッキング
|
||||
fn backtrack(choices: []i32, state: i32, n: i32, res: std.ArrayList(i32)) void {
|
||||
// n 段目に到達したら、方法の数を 1 増やす
|
||||
if (state == n) {
|
||||
res.items[0] = res.items[0] + 1;
|
||||
}
|
||||
// すべての選択肢を走査する
|
||||
for (choices) |choice| {
|
||||
// 枝刈り:n 段目を越えてはならない
|
||||
if (state + choice > n) {
|
||||
continue;
|
||||
}
|
||||
// 試行:選択を行い、状態を更新する
|
||||
backtrack(choices, state + choice, n, res);
|
||||
// 復元
|
||||
}
|
||||
}
|
||||
|
||||
// 階段の上り方:バックトラッキング
|
||||
fn climbingStairsBacktrack(n: usize) !i32 {
|
||||
var choices = [_]i32{ 1, 2 }; // 1 段または 2 段上ることを選択できる
|
||||
var state: i32 = 0; // 0 段目から上り始める
|
||||
var res = std.ArrayList(i32).init(std.heap.page_allocator);
|
||||
defer res.deinit();
|
||||
try res.append(0); // res[0] に方法の数を記録する
|
||||
backtrack(&choices, state, @intCast(n), res);
|
||||
return res.items[0];
|
||||
}
|
||||
|
||||
// 実行用コード
|
||||
pub fn main() !void {
|
||||
var n: usize = 9;
|
||||
|
||||
var res = try climbingStairsBacktrack(n);
|
||||
std.debug.print("{} 段の階段を上る方法は全部で {} 通り\n", .{ n, res });
|
||||
|
||||
_ = try std.io.getStdIn().reader().readByte();
|
||||
}
|
||||
@@ -1,35 +0,0 @@
|
||||
// File: climbing_stairs_constraint_dp.zig
|
||||
// Created Time: 2023-07-15
|
||||
// Author: codingonion (coderonion@gmail.com)
|
||||
|
||||
const std = @import("std");
|
||||
|
||||
// 制約付きの階段の上り方:動的計画法
|
||||
fn climbingStairsConstraintDP(comptime n: usize) i32 {
|
||||
if (n == 1 or n == 2) {
|
||||
return 1;
|
||||
}
|
||||
// 部分問題の解を格納する dp テーブルを初期化する
|
||||
var dp = [_][3]i32{ [_]i32{ -1, -1, -1 } } ** (n + 1);
|
||||
// 初期状態:最小の部分問題の解を設定する
|
||||
dp[1][1] = 1;
|
||||
dp[1][2] = 0;
|
||||
dp[2][1] = 0;
|
||||
dp[2][2] = 1;
|
||||
// 状態遷移:小さな部分問題から順に大きな部分問題を解く
|
||||
for (3..n + 1) |i| {
|
||||
dp[i][1] = dp[i - 1][2];
|
||||
dp[i][2] = dp[i - 2][1] + dp[i - 2][2];
|
||||
}
|
||||
return dp[n][1] + dp[n][2];
|
||||
}
|
||||
|
||||
// 実行用コード
|
||||
pub fn main() !void {
|
||||
comptime var n: usize = 9;
|
||||
|
||||
var res = climbingStairsConstraintDP(n);
|
||||
std.debug.print("{} 段の階段を上る方法は全部で {} 通り\n", .{ n, res });
|
||||
|
||||
_ = try std.io.getStdIn().reader().readByte();
|
||||
}
|
||||
@@ -1,31 +0,0 @@
|
||||
// File: climbing_stairs_dfs.zig
|
||||
// Created Time: 2023-07-15
|
||||
// Author: codingonion (coderonion@gmail.com)
|
||||
|
||||
const std = @import("std");
|
||||
|
||||
// 探索
|
||||
fn dfs(i: usize) i32 {
|
||||
// dp[1] と dp[2] は既知なので、その値を返す
|
||||
if (i == 1 or i == 2) {
|
||||
return @intCast(i);
|
||||
}
|
||||
// dp[i] = dp[i-1] + dp[i-2]
|
||||
var count = dfs(i - 1) + dfs(i - 2);
|
||||
return count;
|
||||
}
|
||||
|
||||
// 階段の上り方:探索
|
||||
fn climbingStairsDFS(comptime n: usize) i32 {
|
||||
return dfs(n);
|
||||
}
|
||||
|
||||
// 実行用コード
|
||||
pub fn main() !void {
|
||||
comptime var n: usize = 9;
|
||||
|
||||
var res = climbingStairsDFS(n);
|
||||
std.debug.print("{} 段の階段を上る方法は全部で {} 通り\n", .{ n, res });
|
||||
|
||||
_ = try std.io.getStdIn().reader().readByte();
|
||||
}
|
||||
@@ -1,39 +0,0 @@
|
||||
// File: climbing_stairs_dfs_mem.zig
|
||||
// Created Time: 2023-07-15
|
||||
// Author: codingonion (coderonion@gmail.com)
|
||||
|
||||
const std = @import("std");
|
||||
|
||||
// メモ化探索
|
||||
fn dfs(i: usize, mem: []i32) i32 {
|
||||
// dp[1] と dp[2] は既知なので、その値を返す
|
||||
if (i == 1 or i == 2) {
|
||||
return @intCast(i);
|
||||
}
|
||||
// dp[i] が記録済みなら、その値をそのまま返す
|
||||
if (mem[i] != -1) {
|
||||
return mem[i];
|
||||
}
|
||||
// dp[i] = dp[i-1] + dp[i-2]
|
||||
var count = dfs(i - 1, mem) + dfs(i - 2, mem);
|
||||
// dp[i] を記録する
|
||||
mem[i] = count;
|
||||
return count;
|
||||
}
|
||||
|
||||
// 階段の上り方:メモ化探索
|
||||
fn climbingStairsDFSMem(comptime n: usize) i32 {
|
||||
// mem[i] は i 段目まで上る方法の総数を記録し、-1 は未記録を表す
|
||||
var mem = [_]i32{ -1 } ** (n + 1);
|
||||
return dfs(n, &mem);
|
||||
}
|
||||
|
||||
// 実行用コード
|
||||
pub fn main() !void {
|
||||
comptime var n: usize = 9;
|
||||
|
||||
var res = climbingStairsDFSMem(n);
|
||||
std.debug.print("{} 段の階段を上る方法は全部で {} 通り\n", .{ n, res });
|
||||
|
||||
_ = try std.io.getStdIn().reader().readByte();
|
||||
}
|
||||
@@ -1,51 +0,0 @@
|
||||
// File: climbing_stairs_dp.zig
|
||||
// Created Time: 2023-07-15
|
||||
// Author: codingonion (coderonion@gmail.com)
|
||||
|
||||
const std = @import("std");
|
||||
|
||||
// 階段の上り方:動的計画法
|
||||
fn climbingStairsDP(comptime n: usize) i32 {
|
||||
// dp[1] と dp[2] は既知なので、その値を返す
|
||||
if (n == 1 or n == 2) {
|
||||
return @intCast(n);
|
||||
}
|
||||
// 部分問題の解を格納する dp テーブルを初期化する
|
||||
var dp = [_]i32{-1} ** (n + 1);
|
||||
// 初期状態:最小の部分問題の解を設定する
|
||||
dp[1] = 1;
|
||||
dp[2] = 2;
|
||||
// 状態遷移:小さな部分問題から順に大きな部分問題を解く
|
||||
for (3..n + 1) |i| {
|
||||
dp[i] = dp[i - 1] + dp[i - 2];
|
||||
}
|
||||
return dp[n];
|
||||
}
|
||||
|
||||
// 階段の上り方:空間を最適化した動的計画法
|
||||
fn climbingStairsDPComp(comptime n: usize) i32 {
|
||||
if (n == 1 or n == 2) {
|
||||
return @intCast(n);
|
||||
}
|
||||
var a: i32 = 1;
|
||||
var b: i32 = 2;
|
||||
for (3..n + 1) |_| {
|
||||
var tmp = b;
|
||||
b = a + b;
|
||||
a = tmp;
|
||||
}
|
||||
return b;
|
||||
}
|
||||
|
||||
// 実行用コード
|
||||
pub fn main() !void {
|
||||
comptime var n: usize = 9;
|
||||
|
||||
var res = climbingStairsDP(n);
|
||||
std.debug.print("{} 段の階段を上る方法は全部で {} 通り\n", .{ n, res });
|
||||
|
||||
res = climbingStairsDPComp(n);
|
||||
std.debug.print("{} 段の階段を上る方法は全部で {} 通り\n", .{ n, res });
|
||||
|
||||
_ = try std.io.getStdIn().reader().readByte();
|
||||
}
|
||||
@@ -1,77 +0,0 @@
|
||||
// File: coin_change.zig
|
||||
// Created Time: 2023-07-15
|
||||
// Author: codingonion (coderonion@gmail.com)
|
||||
|
||||
const std = @import("std");
|
||||
|
||||
// 硬貨の両替:動的計画法
|
||||
fn coinChangeDP(comptime coins: []i32, comptime amt: usize) i32 {
|
||||
comptime var n = coins.len;
|
||||
comptime var max = amt + 1;
|
||||
// dp テーブルを初期化する
|
||||
var dp = [_][amt + 1]i32{[_]i32{0} ** (amt + 1)} ** (n + 1);
|
||||
// 状態遷移:先頭行と先頭列
|
||||
for (1..amt + 1) |a| {
|
||||
dp[0][a] = max;
|
||||
}
|
||||
// 状態遷移:残りの行と列
|
||||
for (1..n + 1) |i| {
|
||||
for (1..amt + 1) |a| {
|
||||
if (coins[i - 1] > @as(i32, @intCast(a))) {
|
||||
// 目標金額を超える場合、硬貨 i を選ばない
|
||||
dp[i][a] = dp[i - 1][a];
|
||||
} else {
|
||||
// 硬貨 i を選ばない場合と選ぶ場合の小さいほうの値
|
||||
dp[i][a] = @min(dp[i - 1][a], dp[i][a - @as(usize, @intCast(coins[i - 1]))] + 1);
|
||||
}
|
||||
}
|
||||
}
|
||||
if (dp[n][amt] != max) {
|
||||
return @intCast(dp[n][amt]);
|
||||
} else {
|
||||
return -1;
|
||||
}
|
||||
}
|
||||
|
||||
// 硬貨の両替:空間を最適化した動的計画法
|
||||
fn coinChangeDPComp(comptime coins: []i32, comptime amt: usize) i32 {
|
||||
comptime var n = coins.len;
|
||||
comptime var max = amt + 1;
|
||||
// dp テーブルを初期化する
|
||||
var dp = [_]i32{0} ** (amt + 1);
|
||||
@memset(&dp, max);
|
||||
dp[0] = 0;
|
||||
// 状態遷移
|
||||
for (1..n + 1) |i| {
|
||||
for (1..amt + 1) |a| {
|
||||
if (coins[i - 1] > @as(i32, @intCast(a))) {
|
||||
// 目標金額を超える場合、硬貨 i を選ばない
|
||||
dp[a] = dp[a];
|
||||
} else {
|
||||
// 硬貨 i を選ばない場合と選ぶ場合の小さいほうの値
|
||||
dp[a] = @min(dp[a], dp[a - @as(usize, @intCast(coins[i - 1]))] + 1);
|
||||
}
|
||||
}
|
||||
}
|
||||
if (dp[amt] != max) {
|
||||
return @intCast(dp[amt]);
|
||||
} else {
|
||||
return -1;
|
||||
}
|
||||
}
|
||||
|
||||
// 実行用コード
|
||||
pub fn main() !void {
|
||||
comptime var coins = [_]i32{ 1, 2, 5 };
|
||||
comptime var amt: usize = 4;
|
||||
|
||||
// 動的計画法
|
||||
var res = coinChangeDP(&coins, amt);
|
||||
std.debug.print("目標金額にするために必要な硬貨の最小枚数は {}\n", .{res});
|
||||
|
||||
// 空間を最適化した動的計画法
|
||||
res = coinChangeDPComp(&coins, amt);
|
||||
std.debug.print("目標金額にするために必要な硬貨の最小枚数は {}\n", .{res});
|
||||
|
||||
_ = try std.io.getStdIn().reader().readByte();
|
||||
}
|
||||
@@ -1,66 +0,0 @@
|
||||
// File: coin_change_ii.zig
|
||||
// Created Time: 2023-07-15
|
||||
// Author: codingonion (coderonion@gmail.com)
|
||||
|
||||
const std = @import("std");
|
||||
|
||||
// 硬貨の両替 II:動的計画法
|
||||
fn coinChangeIIDP(comptime coins: []i32, comptime amt: usize) i32 {
|
||||
comptime var n = coins.len;
|
||||
// dp テーブルを初期化する
|
||||
var dp = [_][amt + 1]i32{[_]i32{0} ** (amt + 1)} ** (n + 1);
|
||||
// 先頭列を初期化する
|
||||
for (0..n + 1) |i| {
|
||||
dp[i][0] = 1;
|
||||
}
|
||||
// 状態遷移
|
||||
for (1..n + 1) |i| {
|
||||
for (1..amt + 1) |a| {
|
||||
if (coins[i - 1] > @as(i32, @intCast(a))) {
|
||||
// 目標金額を超える場合、硬貨 i を選ばない
|
||||
dp[i][a] = dp[i - 1][a];
|
||||
} else {
|
||||
// 硬貨 i を選ばない場合と選ぶ場合の小さいほうの値
|
||||
dp[i][a] = dp[i - 1][a] + dp[i][a - @as(usize, @intCast(coins[i - 1]))];
|
||||
}
|
||||
}
|
||||
}
|
||||
return dp[n][amt];
|
||||
}
|
||||
|
||||
// 硬貨の両替 II:空間を最適化した動的計画法
|
||||
fn coinChangeIIDPComp(comptime coins: []i32, comptime amt: usize) i32 {
|
||||
comptime var n = coins.len;
|
||||
// dp テーブルを初期化する
|
||||
var dp = [_]i32{0} ** (amt + 1);
|
||||
dp[0] = 1;
|
||||
// 状態遷移
|
||||
for (1..n + 1) |i| {
|
||||
for (1..amt + 1) |a| {
|
||||
if (coins[i - 1] > @as(i32, @intCast(a))) {
|
||||
// 目標金額を超える場合、硬貨 i を選ばない
|
||||
dp[a] = dp[a];
|
||||
} else {
|
||||
// 硬貨 i を選ばない場合と選ぶ場合の小さいほうの値
|
||||
dp[a] = dp[a] + dp[a - @as(usize, @intCast(coins[i - 1]))];
|
||||
}
|
||||
}
|
||||
}
|
||||
return dp[amt];
|
||||
}
|
||||
|
||||
// 実行用コード
|
||||
pub fn main() !void {
|
||||
comptime var coins = [_]i32{ 1, 2, 5 };
|
||||
comptime var amt: usize = 5;
|
||||
|
||||
// 動的計画法
|
||||
var res = coinChangeIIDP(&coins, amt);
|
||||
std.debug.print("目標金額になる硬貨の組み合わせの数は {}\n", .{res});
|
||||
|
||||
// 空間を最適化した動的計画法
|
||||
res = coinChangeIIDPComp(&coins, amt);
|
||||
std.debug.print("目標金額になる硬貨の組み合わせの数は {}\n", .{res});
|
||||
|
||||
_ = try std.io.getStdIn().reader().readByte();
|
||||
}
|
||||
@@ -1,146 +0,0 @@
|
||||
// File: edit_distance.zig
|
||||
// Created Time: 2023-07-15
|
||||
// Author: codingonion (coderonion@gmail.com)
|
||||
|
||||
const std = @import("std");
|
||||
|
||||
// 編集距離:全探索
|
||||
fn editDistanceDFS(comptime s: []const u8, comptime t: []const u8, i: usize, j: usize) i32 {
|
||||
// s と t がともに空の場合、0 を返す
|
||||
if (i == 0 and j == 0) {
|
||||
return 0;
|
||||
}
|
||||
// s が空の場合、t の長さを返す
|
||||
if (i == 0) {
|
||||
return @intCast(j);
|
||||
}
|
||||
// t が空の場合、s の長さを返す
|
||||
if (j == 0) {
|
||||
return @intCast(i);
|
||||
}
|
||||
// 2 つの文字が等しい場合、その 2 文字をスキップする
|
||||
if (s[i - 1] == t[j - 1]) {
|
||||
return editDistanceDFS(s, t, i - 1, j - 1);
|
||||
}
|
||||
// 最小編集回数 = 挿入、削除、置換の 3 操作での最小編集回数 + 1
|
||||
var insert = editDistanceDFS(s, t, i, j - 1);
|
||||
var delete = editDistanceDFS(s, t, i - 1, j);
|
||||
var replace = editDistanceDFS(s, t, i - 1, j - 1);
|
||||
// 最小編集回数を返す
|
||||
return @min(@min(insert, delete), replace) + 1;
|
||||
}
|
||||
|
||||
// 編集距離:メモ化探索
|
||||
fn editDistanceDFSMem(comptime s: []const u8, comptime t: []const u8, mem: anytype, i: usize, j: usize) i32 {
|
||||
// s と t がともに空の場合、0 を返す
|
||||
if (i == 0 and j == 0) {
|
||||
return 0;
|
||||
}
|
||||
// s が空の場合、t の長さを返す
|
||||
if (i == 0) {
|
||||
return @intCast(j);
|
||||
}
|
||||
// t が空の場合、s の長さを返す
|
||||
if (j == 0) {
|
||||
return @intCast(i);
|
||||
}
|
||||
// 記録済みなら、その値をそのまま返す
|
||||
if (mem[i][j] != -1) {
|
||||
return mem[i][j];
|
||||
}
|
||||
// 2 つの文字が等しい場合、その 2 文字をスキップする
|
||||
if (s[i - 1] == t[j - 1]) {
|
||||
return editDistanceDFSMem(s, t, mem, i - 1, j - 1);
|
||||
}
|
||||
// 最小編集回数 = 挿入、削除、置換の 3 操作での最小編集回数 + 1
|
||||
var insert = editDistanceDFSMem(s, t, mem, i, j - 1);
|
||||
var delete = editDistanceDFSMem(s, t, mem, i - 1, j);
|
||||
var replace = editDistanceDFSMem(s, t, mem, i - 1, j - 1);
|
||||
// 最小編集回数を記録して返す
|
||||
mem[i][j] = @min(@min(insert, delete), replace) + 1;
|
||||
return mem[i][j];
|
||||
}
|
||||
|
||||
// 編集距離:動的計画法
|
||||
fn editDistanceDP(comptime s: []const u8, comptime t: []const u8) i32 {
|
||||
comptime var n = s.len;
|
||||
comptime var m = t.len;
|
||||
var dp = [_][m + 1]i32{[_]i32{0} ** (m + 1)} ** (n + 1);
|
||||
// 状態遷移:先頭行と先頭列
|
||||
for (1..n + 1) |i| {
|
||||
dp[i][0] = @intCast(i);
|
||||
}
|
||||
for (1..m + 1) |j| {
|
||||
dp[0][j] = @intCast(j);
|
||||
}
|
||||
// 状態遷移:残りの行と列
|
||||
for (1..n + 1) |i| {
|
||||
for (1..m + 1) |j| {
|
||||
if (s[i - 1] == t[j - 1]) {
|
||||
// 2 つの文字が等しい場合、その 2 文字をスキップする
|
||||
dp[i][j] = dp[i - 1][j - 1];
|
||||
} else {
|
||||
// 最小編集回数 = 挿入、削除、置換の 3 操作での最小編集回数 + 1
|
||||
dp[i][j] = @min(@min(dp[i][j - 1], dp[i - 1][j]), dp[i - 1][j - 1]) + 1;
|
||||
}
|
||||
}
|
||||
}
|
||||
return dp[n][m];
|
||||
}
|
||||
|
||||
// 編集距離:空間を最適化した動的計画法
|
||||
fn editDistanceDPComp(comptime s: []const u8, comptime t: []const u8) i32 {
|
||||
comptime var n = s.len;
|
||||
comptime var m = t.len;
|
||||
var dp = [_]i32{0} ** (m + 1);
|
||||
// 状態遷移:先頭行
|
||||
for (1..m + 1) |j| {
|
||||
dp[j] = @intCast(j);
|
||||
}
|
||||
// 状態遷移:残りの行
|
||||
for (1..n + 1) |i| {
|
||||
// 状態遷移:先頭列
|
||||
var leftup = dp[0]; // dp[i-1, j-1] を一時保存する
|
||||
dp[0] = @intCast(i);
|
||||
// 状態遷移:残りの列
|
||||
for (1..m + 1) |j| {
|
||||
var temp = dp[j];
|
||||
if (s[i - 1] == t[j - 1]) {
|
||||
// 2 つの文字が等しい場合、その 2 文字をスキップする
|
||||
dp[j] = leftup;
|
||||
} else {
|
||||
// 最小編集回数 = 挿入、削除、置換の 3 操作での最小編集回数 + 1
|
||||
dp[j] = @min(@min(dp[j - 1], dp[j]), leftup) + 1;
|
||||
}
|
||||
leftup = temp; // 次の反復の dp[i-1, j-1] に更新する
|
||||
}
|
||||
}
|
||||
return dp[m];
|
||||
}
|
||||
|
||||
// 実行用コード
|
||||
pub fn main() !void {
|
||||
const s = "bag";
|
||||
const t = "pack";
|
||||
comptime var n = s.len;
|
||||
comptime var m = t.len;
|
||||
|
||||
// 全探索
|
||||
var res = editDistanceDFS(s, t, n, m);
|
||||
std.debug.print("{s} を {s} に変更するには最低 {} 回の編集が必要\n", .{ s, t, res });
|
||||
|
||||
// メモ化探索
|
||||
var mem = [_][m + 1]i32{[_]i32{-1} ** (m + 1)} ** (n + 1);
|
||||
res = editDistanceDFSMem(s, t, @constCast(&mem), n, m);
|
||||
std.debug.print("{s} を {s} に変更するには最低 {} 回の編集が必要\n", .{ s, t, res });
|
||||
|
||||
// 動的計画法
|
||||
res = editDistanceDP(s, t);
|
||||
std.debug.print("{s} を {s} に変更するには最低 {} 回の編集が必要\n", .{ s, t, res });
|
||||
|
||||
// 空間を最適化した動的計画法
|
||||
res = editDistanceDPComp(s, t);
|
||||
std.debug.print("{s} を {s} に変更するには最低 {} 回の編集が必要\n", .{ s, t, res });
|
||||
|
||||
_ = try std.io.getStdIn().reader().readByte();
|
||||
}
|
||||
@@ -1,110 +0,0 @@
|
||||
// File: knapsack.zig
|
||||
// Created Time: 2023-07-15
|
||||
// Author: codingonion (coderonion@gmail.com)
|
||||
|
||||
const std = @import("std");
|
||||
|
||||
// 0-1 ナップサック問題:全探索
|
||||
fn knapsackDFS(wgt: []i32, val: []i32, i: usize, c: usize) i32 {
|
||||
// すべての品物を選び終えたか、ナップサックの残り容量がなければ、価値 0 を返す
|
||||
if (i == 0 or c == 0) {
|
||||
return 0;
|
||||
}
|
||||
// ナップサックの容量を超える場合、入れない選択しかできない
|
||||
if (wgt[i - 1] > c) {
|
||||
return knapsackDFS(wgt, val, i - 1, c);
|
||||
}
|
||||
// 品物 i を入れない場合と入れる場合の最大価値を計算する
|
||||
var no = knapsackDFS(wgt, val, i - 1, c);
|
||||
var yes = knapsackDFS(wgt, val, i - 1, c - @as(usize, @intCast(wgt[i - 1]))) + val[i - 1];
|
||||
// 2 通りの選択のうち、価値が大きいほうを返す
|
||||
return @max(no, yes);
|
||||
}
|
||||
|
||||
// 0-1 ナップサック問題:メモ化探索
|
||||
fn knapsackDFSMem(wgt: []i32, val: []i32, mem: anytype, i: usize, c: usize) i32 {
|
||||
// すべての品物を選び終えたか、ナップサックの残り容量がなければ、価値 0 を返す
|
||||
if (i == 0 or c == 0) {
|
||||
return 0;
|
||||
}
|
||||
// 記録済みなら、その値をそのまま返す
|
||||
if (mem[i][c] != -1) {
|
||||
return mem[i][c];
|
||||
}
|
||||
// ナップサックの容量を超える場合、入れない選択しかできない
|
||||
if (wgt[i - 1] > c) {
|
||||
return knapsackDFSMem(wgt, val, mem, i - 1, c);
|
||||
}
|
||||
// 品物 i を入れない場合と入れる場合の最大価値を計算する
|
||||
var no = knapsackDFSMem(wgt, val, mem, i - 1, c);
|
||||
var yes = knapsackDFSMem(wgt, val, mem, i - 1, c - @as(usize, @intCast(wgt[i - 1]))) + val[i - 1];
|
||||
// 2 通りの選択のうち、価値が大きいほうを記録して返す
|
||||
mem[i][c] = @max(no, yes);
|
||||
return mem[i][c];
|
||||
}
|
||||
|
||||
// 0-1 ナップサック問題:動的計画法
|
||||
fn knapsackDP(comptime wgt: []i32, val: []i32, comptime cap: usize) i32 {
|
||||
comptime var n = wgt.len;
|
||||
// dp テーブルを初期化する
|
||||
var dp = [_][cap + 1]i32{[_]i32{0} ** (cap + 1)} ** (n + 1);
|
||||
// 状態遷移
|
||||
for (1..n + 1) |i| {
|
||||
for (1..cap + 1) |c| {
|
||||
if (wgt[i - 1] > c) {
|
||||
// ナップサックの容量を超える場合、品物 i を選ばない
|
||||
dp[i][c] = dp[i - 1][c];
|
||||
} else {
|
||||
// 品物 i を選ばない場合と選ぶ場合の大きいほうの値
|
||||
dp[i][c] = @max(dp[i - 1][c], dp[i - 1][c - @as(usize, @intCast(wgt[i - 1]))] + val[i - 1]);
|
||||
}
|
||||
}
|
||||
}
|
||||
return dp[n][cap];
|
||||
}
|
||||
|
||||
// 0-1 ナップサック問題:空間を最適化した動的計画法
|
||||
fn knapsackDPComp(wgt: []i32, val: []i32, comptime cap: usize) i32 {
|
||||
var n = wgt.len;
|
||||
// dp テーブルを初期化する
|
||||
var dp = [_]i32{0} ** (cap + 1);
|
||||
// 状態遷移
|
||||
for (1..n + 1) |i| {
|
||||
// 逆順に走査する
|
||||
var c = cap;
|
||||
while (c > 0) : (c -= 1) {
|
||||
if (wgt[i - 1] < c) {
|
||||
// 品物 i を選ばない場合と選ぶ場合の大きいほうの値
|
||||
dp[c] = @max(dp[c], dp[c - @as(usize, @intCast(wgt[i - 1]))] + val[i - 1]);
|
||||
}
|
||||
}
|
||||
}
|
||||
return dp[cap];
|
||||
}
|
||||
|
||||
// 実行用コード
|
||||
pub fn main() !void {
|
||||
comptime var wgt = [_]i32{ 10, 20, 30, 40, 50 };
|
||||
comptime var val = [_]i32{ 50, 120, 150, 210, 240 };
|
||||
comptime var cap = 50;
|
||||
comptime var n = wgt.len;
|
||||
|
||||
// 全探索
|
||||
var res = knapsackDFS(&wgt, &val, n, cap);
|
||||
std.debug.print("ナップサックの容量を超えない品物の最大価値は {}\n", .{res});
|
||||
|
||||
// メモ化探索
|
||||
var mem = [_][cap + 1]i32{[_]i32{-1} ** (cap + 1)} ** (n + 1);
|
||||
res = knapsackDFSMem(&wgt, &val, @constCast(&mem), n, cap);
|
||||
std.debug.print("ナップサックの容量を超えない品物の最大価値は {}\n", .{res});
|
||||
|
||||
// 動的計画法
|
||||
res = knapsackDP(&wgt, &val, cap);
|
||||
std.debug.print("ナップサックの容量を超えない品物の最大価値は {}\n", .{res});
|
||||
|
||||
// 空間を最適化した動的計画法
|
||||
res = knapsackDPComp(&wgt, &val, cap);
|
||||
std.debug.print("ナップサックの容量を超えない品物の最大価値は {}\n", .{res});
|
||||
|
||||
_ = try std.io.getStdIn().reader().readByte();
|
||||
}
|
||||
@@ -1,54 +0,0 @@
|
||||
// File: min_cost_climbing_stairs_dp.zig
|
||||
// Created Time: 2023-07-15
|
||||
// Author: codingonion (coderonion@gmail.com)
|
||||
|
||||
const std = @import("std");
|
||||
|
||||
// 階段を上る最小コスト:動的計画法
|
||||
fn minCostClimbingStairsDP(comptime cost: []i32) i32 {
|
||||
comptime var n = cost.len - 1;
|
||||
if (n == 1 or n == 2) {
|
||||
return cost[n];
|
||||
}
|
||||
// 部分問題の解を格納する dp テーブルを初期化する
|
||||
var dp = [_]i32{-1} ** (n + 1);
|
||||
// 初期状態:最小の部分問題の解を設定する
|
||||
dp[1] = cost[1];
|
||||
dp[2] = cost[2];
|
||||
// 状態遷移:小さな部分問題から順に大きな部分問題を解く
|
||||
for (3..n + 1) |i| {
|
||||
dp[i] = @min(dp[i - 1], dp[i - 2]) + cost[i];
|
||||
}
|
||||
return dp[n];
|
||||
}
|
||||
|
||||
// 階段を上る最小コスト:空間を最適化した動的計画法
|
||||
fn minCostClimbingStairsDPComp(cost: []i32) i32 {
|
||||
var n = cost.len - 1;
|
||||
if (n == 1 or n == 2) {
|
||||
return cost[n];
|
||||
}
|
||||
var a = cost[1];
|
||||
var b = cost[2];
|
||||
// 状態遷移:小さな部分問題から順に大きな部分問題を解く
|
||||
for (3..n + 1) |i| {
|
||||
var tmp = b;
|
||||
b = @min(a, tmp) + cost[i];
|
||||
a = tmp;
|
||||
}
|
||||
return b;
|
||||
}
|
||||
|
||||
// 実行用コード
|
||||
pub fn main() !void {
|
||||
comptime var cost = [_]i32{ 0, 1, 10, 1, 1, 1, 10, 1, 1, 10, 1 };
|
||||
std.debug.print("入力した階段のコストのリストは {any}\n", .{cost});
|
||||
|
||||
var res = minCostClimbingStairsDP(&cost);
|
||||
std.debug.print("入力した階段のコストのリストは {}\n", .{res});
|
||||
|
||||
res = minCostClimbingStairsDPComp(&cost);
|
||||
std.debug.print("入力した階段のコストのリストは {}\n", .{res});
|
||||
|
||||
_ = try std.io.getStdIn().reader().readByte();
|
||||
}
|
||||
@@ -1,122 +0,0 @@
|
||||
// File: min_path_sum.zig
|
||||
// Created Time: 2023-07-15
|
||||
// Author: codingonion (coderonion@gmail.com)
|
||||
|
||||
const std = @import("std");
|
||||
|
||||
// 最小経路和:全探索
|
||||
fn minPathSumDFS(grid: anytype, i: i32, j: i32) i32 {
|
||||
// 左上のセルなら探索を終了する
|
||||
if (i == 0 and j == 0) {
|
||||
return grid[0][0];
|
||||
}
|
||||
// 行または列のインデックスが範囲外の場合、コスト +∞ を返す
|
||||
if (i < 0 or j < 0) {
|
||||
return std.math.maxInt(i32);
|
||||
}
|
||||
// 左上から (i-1, j) および (i, j-1) までの最小経路コストを計算する
|
||||
var up = minPathSumDFS(grid, i - 1, j);
|
||||
var left = minPathSumDFS(grid, i, j - 1);
|
||||
// 左上から (i, j) までの最小経路コストを返す
|
||||
return @min(left, up) + grid[@as(usize, @intCast(i))][@as(usize, @intCast(j))];
|
||||
}
|
||||
|
||||
// 最小経路和:メモ化探索
|
||||
fn minPathSumDFSMem(grid: anytype, mem: anytype, i: i32, j: i32) i32 {
|
||||
// 左上のセルなら探索を終了する
|
||||
if (i == 0 and j == 0) {
|
||||
return grid[0][0];
|
||||
}
|
||||
// 行または列のインデックスが範囲外の場合、コスト +∞ を返す
|
||||
if (i < 0 or j < 0) {
|
||||
return std.math.maxInt(i32);
|
||||
}
|
||||
// 記録済みなら、その値をそのまま返す
|
||||
if (mem[@as(usize, @intCast(i))][@as(usize, @intCast(j))] != -1) {
|
||||
return mem[@as(usize, @intCast(i))][@as(usize, @intCast(j))];
|
||||
}
|
||||
// 左上から (i-1, j) および (i, j-1) までの最小経路コストを計算する
|
||||
var up = minPathSumDFSMem(grid, mem, i - 1, j);
|
||||
var left = minPathSumDFSMem(grid, mem, i, j - 1);
|
||||
// 左上から (i, j) までの最小経路コストを返す
|
||||
// 左上から (i, j) までの最小経路コストを記録して返す
|
||||
mem[@as(usize, @intCast(i))][@as(usize, @intCast(j))] = @min(left, up) + grid[@as(usize, @intCast(i))][@as(usize, @intCast(j))];
|
||||
return mem[@as(usize, @intCast(i))][@as(usize, @intCast(j))];
|
||||
}
|
||||
|
||||
// 最小経路和:動的計画法
|
||||
fn minPathSumDP(comptime grid: anytype) i32 {
|
||||
comptime var n = grid.len;
|
||||
comptime var m = grid[0].len;
|
||||
// dp テーブルを初期化する
|
||||
var dp = [_][m]i32{[_]i32{0} ** m} ** n;
|
||||
dp[0][0] = grid[0][0];
|
||||
// 状態遷移:先頭行
|
||||
for (1..m) |j| {
|
||||
dp[0][j] = dp[0][j - 1] + grid[0][j];
|
||||
}
|
||||
// 状態遷移:先頭列
|
||||
for (1..n) |i| {
|
||||
dp[i][0] = dp[i - 1][0] + grid[i][0];
|
||||
}
|
||||
// 状態遷移:残りの行と列
|
||||
for (1..n) |i| {
|
||||
for (1..m) |j| {
|
||||
dp[i][j] = @min(dp[i][j - 1], dp[i - 1][j]) + grid[i][j];
|
||||
}
|
||||
}
|
||||
return dp[n - 1][m - 1];
|
||||
}
|
||||
|
||||
// 最小経路和:空間を最適化した動的計画法
|
||||
fn minPathSumDPComp(comptime grid: anytype) i32 {
|
||||
comptime var n = grid.len;
|
||||
comptime var m = grid[0].len;
|
||||
// dp テーブルを初期化する
|
||||
var dp = [_]i32{0} ** m;
|
||||
// 状態遷移:先頭行
|
||||
dp[0] = grid[0][0];
|
||||
for (1..m) |j| {
|
||||
dp[j] = dp[j - 1] + grid[0][j];
|
||||
}
|
||||
// 状態遷移:残りの行
|
||||
for (1..n) |i| {
|
||||
// 状態遷移:先頭列
|
||||
dp[0] = dp[0] + grid[i][0];
|
||||
for (1..m) |j| {
|
||||
dp[j] = @min(dp[j - 1], dp[j]) + grid[i][j];
|
||||
}
|
||||
}
|
||||
return dp[m - 1];
|
||||
}
|
||||
|
||||
// 実行用コード
|
||||
pub fn main() !void {
|
||||
comptime var grid = [_][4]i32{
|
||||
[_]i32{ 1, 3, 1, 5 },
|
||||
[_]i32{ 2, 2, 4, 2 },
|
||||
[_]i32{ 5, 3, 2, 1 },
|
||||
[_]i32{ 4, 3, 5, 2 },
|
||||
};
|
||||
comptime var n = grid.len;
|
||||
comptime var m = grid[0].len;
|
||||
|
||||
// 全探索
|
||||
var res = minPathSumDFS(&grid, n - 1, m - 1);
|
||||
std.debug.print("左上から右下までの最小経路和は {}\n", .{res});
|
||||
|
||||
// メモ化探索
|
||||
var mem = [_][m]i32{[_]i32{-1} ** m} ** n;
|
||||
res = minPathSumDFSMem(&grid, &mem, n - 1, m - 1);
|
||||
std.debug.print("左上から右下までの最小経路和は {}\n", .{res});
|
||||
|
||||
// 動的計画法
|
||||
res = minPathSumDP(&grid);
|
||||
std.debug.print("左上から右下までの最小経路和は {}\n", .{res});
|
||||
|
||||
// 空間を最適化した動的計画法
|
||||
res = minPathSumDPComp(&grid);
|
||||
std.debug.print("左上から右下までの最小経路和は {}\n", .{res});
|
||||
|
||||
_ = try std.io.getStdIn().reader().readByte();
|
||||
}
|
||||
@@ -1,62 +0,0 @@
|
||||
// File: unbounded_knapsack.zig
|
||||
// Created Time: 2023-07-15
|
||||
// Author: codingonion (coderonion@gmail.com)
|
||||
|
||||
const std = @import("std");
|
||||
|
||||
// 個数制限なしナップサック問題:動的計画法
|
||||
fn unboundedKnapsackDP(comptime wgt: []i32, val: []i32, comptime cap: usize) i32 {
|
||||
comptime var n = wgt.len;
|
||||
// dp テーブルを初期化する
|
||||
var dp = [_][cap + 1]i32{[_]i32{0} ** (cap + 1)} ** (n + 1);
|
||||
// 状態遷移
|
||||
for (1..n + 1) |i| {
|
||||
for (1..cap + 1) |c| {
|
||||
if (wgt[i - 1] > c) {
|
||||
// ナップサックの容量を超える場合、品物 i を選ばない
|
||||
dp[i][c] = dp[i - 1][c];
|
||||
} else {
|
||||
// 品物 i を選ばない場合と選ぶ場合の大きいほうの値
|
||||
dp[i][c] = @max(dp[i - 1][c], dp[i][c - @as(usize, @intCast(wgt[i - 1]))] + val[i - 1]);
|
||||
}
|
||||
}
|
||||
}
|
||||
return dp[n][cap];
|
||||
}
|
||||
|
||||
// 個数制限なしナップサック問題:空間を最適化した動的計画法
|
||||
fn unboundedKnapsackDPComp(comptime wgt: []i32, val: []i32, comptime cap: usize) i32 {
|
||||
comptime var n = wgt.len;
|
||||
// dp テーブルを初期化する
|
||||
var dp = [_]i32{0} ** (cap + 1);
|
||||
// 状態遷移
|
||||
for (1..n + 1) |i| {
|
||||
for (1..cap + 1) |c| {
|
||||
if (wgt[i - 1] > c) {
|
||||
// ナップサックの容量を超える場合、品物 i を選ばない
|
||||
dp[c] = dp[c];
|
||||
} else {
|
||||
// 品物 i を選ばない場合と選ぶ場合の大きいほうの値
|
||||
dp[c] = @max(dp[c], dp[c - @as(usize, @intCast(wgt[i - 1]))] + val[i - 1]);
|
||||
}
|
||||
}
|
||||
}
|
||||
return dp[cap];
|
||||
}
|
||||
|
||||
// 実行用コード
|
||||
pub fn main() !void {
|
||||
comptime var wgt = [_]i32{ 1, 2, 3 };
|
||||
comptime var val = [_]i32{ 5, 11, 15 };
|
||||
comptime var cap = 4;
|
||||
|
||||
// 動的計画法
|
||||
var res = unboundedKnapsackDP(&wgt, &val, cap);
|
||||
std.debug.print("ナップサックの容量を超えない品物の最大価値は {}\n", .{res});
|
||||
|
||||
// 空間を最適化した動的計画法
|
||||
res = unboundedKnapsackDPComp(&wgt, &val, cap);
|
||||
std.debug.print("ナップサックの容量を超えない品物の最大価値は {}\n", .{res});
|
||||
|
||||
_ = try std.io.getStdIn().reader().readByte();
|
||||
}
|
||||
@@ -1,162 +0,0 @@
|
||||
// File: array_hash_map.zig
|
||||
// Created Time: 2023-01-15
|
||||
// Author: codingonion (coderonion@gmail.com)
|
||||
|
||||
const std = @import("std");
|
||||
const inc = @import("include");
|
||||
|
||||
// キーと値のペア
|
||||
const Pair = struct {
|
||||
key: usize = undefined,
|
||||
val: []const u8 = undefined,
|
||||
|
||||
pub fn init(key: usize, val: []const u8) Pair {
|
||||
return Pair {
|
||||
.key = key,
|
||||
.val = val,
|
||||
};
|
||||
}
|
||||
};
|
||||
|
||||
// 配列で実装したハッシュテーブル
|
||||
pub 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 = Pair.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 pairSet(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.pairSet();
|
||||
defer entry_set.deinit();
|
||||
for (entry_set.items) |item| {
|
||||
std.debug.print("{} -> {s}\n", .{item.key, item.val});
|
||||
}
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
// 実行用コード
|
||||
pub fn main() !void {
|
||||
// ハッシュテーブルを初期化する
|
||||
var map = ArrayHashMap(Pair){};
|
||||
try map.init(std.heap.page_allocator);
|
||||
defer map.deinit();
|
||||
|
||||
// 追加操作
|
||||
// ハッシュテーブルにキーと値のペア (key, value) を追加する
|
||||
try map.put(12836, "小哈");
|
||||
try map.put(15937, "小啰");
|
||||
try map.put(16750, "小算");
|
||||
try map.put(13276, "小法");
|
||||
try map.put(10583, "小鸭");
|
||||
std.debug.print("\n追加後のハッシュテーブル\nKey -> Value\n", .{});
|
||||
try map.print();
|
||||
|
||||
// 取得操作
|
||||
// ハッシュテーブルにキー key を渡し、値 value を取得する
|
||||
var name = map.get(15937);
|
||||
std.debug.print("\n学生番号 15937 に対応する氏名は {s}\n", .{name});
|
||||
|
||||
// 削除操作
|
||||
// ハッシュテーブルからキーと値のペア (key, value) を削除する
|
||||
try map.remove(10583);
|
||||
std.debug.print("\n10583 を削除した後のハッシュテーブル\nKey -> Value\n", .{});
|
||||
try map.print();
|
||||
|
||||
// ハッシュテーブルを走査する
|
||||
std.debug.print("\nキーと値のペア Key->Value を走査する\n", .{});
|
||||
var entry_set = try map.pairSet();
|
||||
for (entry_set.items) |kv| {
|
||||
std.debug.print("{} -> {s}\n", .{kv.key, kv.val});
|
||||
}
|
||||
defer entry_set.deinit();
|
||||
std.debug.print("\nキー Key だけを走査する\n", .{});
|
||||
var key_set = try map.keySet();
|
||||
for (key_set.items) |key| {
|
||||
std.debug.print("{}\n", .{key});
|
||||
}
|
||||
defer key_set.deinit();
|
||||
std.debug.print("\n値 value だけを走査する\n", .{});
|
||||
var value_set = try map.valueSet();
|
||||
for (value_set.items) |val| {
|
||||
std.debug.print("{s}\n", .{val});
|
||||
}
|
||||
defer value_set.deinit();
|
||||
|
||||
_ = try std.io.getStdIn().reader().readByte();
|
||||
}
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user