mirror of
https://github.com/krahets/hello-algo.git
synced 2026-11-29 07:44:46 +08:00
Retranslate the complete English edition from Simplified Chinese (#2010)
* Retranslate the complete English edition from Simplified Chinese * Polish three English explanations after reader-focused review
This commit is contained in:
91
en/codes/zig/chapter_computational_complexity/iteration.zig
Normal file
91
en/codes/zig/chapter_computational_complexity/iteration.zig
Normal file
@@ -0,0 +1,91 @@
|
||||
// File: iteration.zig
|
||||
// Created Time: 2023-09-27
|
||||
// Author: QiLOL (pikaqqpika@gmail.com), CreatorMetaSky (creator_meta_sky@163.com)
|
||||
|
||||
const std = @import("std");
|
||||
const Allocator = std.mem.Allocator;
|
||||
|
||||
// for loop
|
||||
fn forLoop(n: usize) i32 {
|
||||
var res: i32 = 0;
|
||||
// Sum 1, 2, ..., n-1, n in a loop
|
||||
for (1..n + 1) |i| {
|
||||
res += @intCast(i);
|
||||
}
|
||||
return res;
|
||||
}
|
||||
|
||||
// while loop
|
||||
fn whileLoop(n: i32) i32 {
|
||||
var res: i32 = 0;
|
||||
var i: i32 = 1; // Initialize the loop control variable
|
||||
// Sum 1, 2, ..., n-1, n in a loop
|
||||
while (i <= n) : (i += 1) {
|
||||
res += @intCast(i);
|
||||
}
|
||||
return res;
|
||||
}
|
||||
|
||||
// while loop (two updates)
|
||||
fn whileLoopII(n: i32) i32 {
|
||||
var res: i32 = 0;
|
||||
var i: i32 = 1; // Initialize the loop control variable
|
||||
// Sum 1, 4, 10, ... in a loop
|
||||
while (i <= n) : ({
|
||||
// Update the loop control variable
|
||||
i += 1;
|
||||
i *= 2;
|
||||
}) {
|
||||
res += @intCast(i);
|
||||
}
|
||||
return res;
|
||||
}
|
||||
|
||||
// Nested for loops
|
||||
fn nestedForLoop(allocator: Allocator, n: usize) ![]const u8 {
|
||||
var res = std.ArrayList(u8).init(allocator);
|
||||
defer res.deinit();
|
||||
var buffer: [20]u8 = undefined;
|
||||
// Loop over i = 1, 2, ..., n-1, n
|
||||
for (1..n + 1) |i| {
|
||||
// Loop over j = 1, 2, ..., n-1, n
|
||||
for (1..n + 1) |j| {
|
||||
const str = try std.fmt.bufPrint(&buffer, "({d}, {d}), ", .{ i, j });
|
||||
try res.appendSlice(str);
|
||||
}
|
||||
}
|
||||
return res.toOwnedSlice();
|
||||
}
|
||||
|
||||
// Driver code
|
||||
pub fn run() !void {
|
||||
var gpa = std.heap.DebugAllocator(.{}){};
|
||||
defer _ = gpa.deinit();
|
||||
const allocator = gpa.allocator();
|
||||
|
||||
const n: i32 = 5;
|
||||
var res: i32 = 0;
|
||||
|
||||
res = forLoop(n);
|
||||
std.debug.print("Sum computed by the for loop: res = {}\n", .{res});
|
||||
|
||||
res = whileLoop(n);
|
||||
std.debug.print("Sum computed by the while loop: res = {}\n", .{res});
|
||||
|
||||
res = whileLoopII(n);
|
||||
std.debug.print("Sum computed by the while loop with two updates: res = {}\n", .{res});
|
||||
|
||||
const resStr = try nestedForLoop(allocator, n);
|
||||
std.debug.print("Nested for-loop traversal: {s}\n", .{resStr});
|
||||
allocator.free(resStr);
|
||||
|
||||
std.debug.print("\n", .{});
|
||||
}
|
||||
|
||||
pub fn main() !void {
|
||||
try run();
|
||||
}
|
||||
|
||||
test "interation" {
|
||||
try run();
|
||||
}
|
||||
88
en/codes/zig/chapter_computational_complexity/recursion.zig
Normal file
88
en/codes/zig/chapter_computational_complexity/recursion.zig
Normal file
@@ -0,0 +1,88 @@
|
||||
// File: recursion.zig
|
||||
// Created Time: 2023-09-27
|
||||
// Author: QiLOL (pikaqqpika@gmail.com), CreatorMetaSky (creator_meta_sky@163.com)
|
||||
|
||||
const std = @import("std");
|
||||
|
||||
// Recursive function
|
||||
fn recur(n: i32) i32 {
|
||||
// Base case
|
||||
if (n == 1) {
|
||||
return 1;
|
||||
}
|
||||
// Recurse: make a recursive call
|
||||
const res = recur(n - 1);
|
||||
// Unwind: return the result
|
||||
return n + res;
|
||||
}
|
||||
|
||||
// Simulate recursion using iteration
|
||||
fn forLoopRecur(comptime n: i32) i32 {
|
||||
// Use an explicit stack to simulate the system call stack
|
||||
var stack: [n]i32 = undefined;
|
||||
var res: i32 = 0;
|
||||
// Simulate recursive descent by filling the explicit stack
|
||||
var i: usize = n;
|
||||
while (i > 0) {
|
||||
stack[i - 1] = @intCast(i);
|
||||
i -= 1;
|
||||
}
|
||||
// Simulate unwinding by accumulating the stored values
|
||||
var index: usize = n;
|
||||
while (index > 0) {
|
||||
index -= 1;
|
||||
res += stack[index];
|
||||
}
|
||||
// res = 1+2+3+...+n
|
||||
return res;
|
||||
}
|
||||
|
||||
// Tail-recursive function
|
||||
fn tailRecur(n: i32, res: i32) i32 {
|
||||
// Base case
|
||||
if (n == 0) {
|
||||
return res;
|
||||
}
|
||||
// Tail-recursive call
|
||||
return tailRecur(n - 1, res + n);
|
||||
}
|
||||
|
||||
// Fibonacci sequence
|
||||
fn fib(n: i32) i32 {
|
||||
// Base cases: f(1) = 0, f(2) = 1
|
||||
if (n == 1 or n == 2) {
|
||||
return n - 1;
|
||||
}
|
||||
// Recursive calls: f(n) = f(n-1) + f(n-2)
|
||||
const res: i32 = fib(n - 1) + fib(n - 2);
|
||||
// Return the result f(n)
|
||||
return res;
|
||||
}
|
||||
|
||||
// Driver code
|
||||
pub fn run() void {
|
||||
const n: i32 = 5;
|
||||
var res: i32 = 0;
|
||||
|
||||
res = recur(n);
|
||||
std.debug.print("Sum computed by recursion: res = {}\n", .{recur(n)});
|
||||
|
||||
res = forLoopRecur(n);
|
||||
std.debug.print("Sum computed by simulating recursion with iteration: res = {}\n", .{forLoopRecur(n)});
|
||||
|
||||
res = tailRecur(n, 0);
|
||||
std.debug.print("Sum computed by tail recursion: res = {}\n", .{tailRecur(n, 0)});
|
||||
|
||||
res = fib(n);
|
||||
std.debug.print("Term {} of the Fibonacci sequence is {}\n", .{ n, fib(n) });
|
||||
|
||||
std.debug.print("\n", .{});
|
||||
}
|
||||
|
||||
pub fn main() void {
|
||||
run();
|
||||
}
|
||||
|
||||
test "recursion" {
|
||||
run();
|
||||
}
|
||||
@@ -0,0 +1,142 @@
|
||||
// File: space_complexity.zig
|
||||
// Created Time: 2023-01-07
|
||||
// Author: codingonion (coderonion@gmail.com), CreatorMetaSky (creator_meta_sky@163.com)
|
||||
|
||||
const std = @import("std");
|
||||
const utils = @import("utils");
|
||||
const ListNode = utils.ListNode;
|
||||
const TreeNode = utils.TreeNode;
|
||||
|
||||
// Function
|
||||
fn function() i32 {
|
||||
// Perform some operations
|
||||
return 0;
|
||||
}
|
||||
|
||||
// Constant complexity
|
||||
fn constant(n: i32) void {
|
||||
// Constants, variables, and objects occupy O(1) space
|
||||
const a: i32 = 0;
|
||||
const b: i32 = 0;
|
||||
const nums = [_]i32{0} ** 10000;
|
||||
const node = ListNode(i32){ .val = 0 };
|
||||
var i: i32 = 0;
|
||||
// Variables in the loop occupy O(1) space
|
||||
while (i < n) : (i += 1) {
|
||||
const c: i32 = 0;
|
||||
_ = c;
|
||||
}
|
||||
// Function calls in the loop occupy O(1) space
|
||||
i = 0;
|
||||
while (i < n) : (i += 1) {
|
||||
_ = function();
|
||||
}
|
||||
_ = a;
|
||||
_ = b;
|
||||
_ = nums;
|
||||
_ = node;
|
||||
}
|
||||
|
||||
// Linear complexity
|
||||
fn linear(comptime n: i32) !void {
|
||||
// An array of length n uses O(n) space
|
||||
const nums = [_]i32{0} ** n;
|
||||
// A list of length n occupies O(n) space
|
||||
var nodes = std.ArrayList(i32).init(std.heap.page_allocator);
|
||||
defer nodes.deinit();
|
||||
var i: i32 = 0;
|
||||
while (i < n) : (i += 1) {
|
||||
try nodes.append(i);
|
||||
}
|
||||
// A hash table containing n entries would occupy O(n) space
|
||||
var map = std.AutoArrayHashMap(i32, []const u8).init(std.heap.page_allocator);
|
||||
defer map.deinit();
|
||||
var j: i32 = 0;
|
||||
while (j < n) : (j += 1) {
|
||||
const string = try std.fmt.allocPrint(std.heap.page_allocator, "{d}", .{j});
|
||||
defer std.heap.page_allocator.free(string);
|
||||
try map.put(i, string);
|
||||
}
|
||||
_ = nums;
|
||||
}
|
||||
|
||||
// Linear complexity (recursive implementation)
|
||||
fn linearRecur(comptime n: i32) void {
|
||||
std.debug.print("Recursion: n = {}\n", .{n});
|
||||
if (n == 1) return;
|
||||
linearRecur(n - 1);
|
||||
}
|
||||
|
||||
// Quadratic complexity
|
||||
fn quadratic(n: i32) !void {
|
||||
// A two-dimensional list retaining n by n elements would occupy O(n^2) space
|
||||
var nodes = std.ArrayList(std.ArrayList(i32)).init(std.heap.page_allocator);
|
||||
defer nodes.deinit();
|
||||
var i: i32 = 0;
|
||||
while (i < n) : (i += 1) {
|
||||
var tmp = std.ArrayList(i32).init(std.heap.page_allocator);
|
||||
defer tmp.deinit();
|
||||
var j: i32 = 0;
|
||||
while (j < n) : (j += 1) {
|
||||
try tmp.append(0);
|
||||
}
|
||||
try nodes.append(tmp);
|
||||
}
|
||||
}
|
||||
|
||||
// Quadratic complexity (recursive implementation)
|
||||
fn quadraticRecur(comptime n: i32) i32 {
|
||||
if (n <= 0) return 0;
|
||||
const nums = [_]i32{0} ** n;
|
||||
std.debug.print("In the recursive call with n = {}, nums has length {}\n", .{ n, nums.len });
|
||||
return quadraticRecur(n - 1);
|
||||
}
|
||||
|
||||
// Exponential complexity (building a perfect binary tree)
|
||||
fn buildTree(allocator: std.mem.Allocator, n: i32) !?*TreeNode(i32) {
|
||||
if (n == 0) return null;
|
||||
const root = try allocator.create(TreeNode(i32));
|
||||
root.init(0);
|
||||
root.left = try buildTree(allocator, n - 1);
|
||||
root.right = try buildTree(allocator, n - 1);
|
||||
return root;
|
||||
}
|
||||
|
||||
// Free the tree's memory
|
||||
fn freeTree(allocator: std.mem.Allocator, root: ?*const TreeNode(i32)) void {
|
||||
if (root == null) return;
|
||||
freeTree(allocator, root.?.left);
|
||||
freeTree(allocator, root.?.right);
|
||||
allocator.destroy(root.?);
|
||||
}
|
||||
|
||||
// Driver code
|
||||
pub fn run() !void {
|
||||
var gpa = std.heap.DebugAllocator(.{}){};
|
||||
defer _ = gpa.deinit();
|
||||
const allocator = gpa.allocator();
|
||||
|
||||
const n: i32 = 5;
|
||||
// Constant complexity
|
||||
constant(n);
|
||||
// Linear complexity
|
||||
try linear(n);
|
||||
linearRecur(n);
|
||||
// Quadratic complexity
|
||||
try quadratic(n);
|
||||
_ = quadraticRecur(n);
|
||||
// Exponential complexity
|
||||
const root = try buildTree(allocator, n);
|
||||
defer freeTree(allocator, root);
|
||||
std.debug.print("{}\n", .{utils.fmt.tree(i32, root)});
|
||||
|
||||
std.debug.print("\n", .{});
|
||||
}
|
||||
|
||||
pub fn main() !void {
|
||||
try run();
|
||||
}
|
||||
|
||||
test "space_complexity" {
|
||||
try run();
|
||||
}
|
||||
@@ -0,0 +1,184 @@
|
||||
// File: time_complexity.zig
|
||||
// Created Time: 2022-12-28
|
||||
// Author: codingonion (coderonion@gmail.com), CreatorMetaSky (creator_meta_sky@163.com)
|
||||
|
||||
const std = @import("std");
|
||||
|
||||
// Constant complexity
|
||||
fn constant(n: i32) i32 {
|
||||
_ = n;
|
||||
var count: i32 = 0;
|
||||
const size: i32 = 100_000;
|
||||
var i: i32 = 0;
|
||||
while (i < size) : (i += 1) {
|
||||
count += 1;
|
||||
}
|
||||
return count;
|
||||
}
|
||||
|
||||
// Linear complexity
|
||||
fn linear(n: i32) i32 {
|
||||
var count: i32 = 0;
|
||||
var i: i32 = 0;
|
||||
while (i < n) : (i += 1) {
|
||||
count += 1;
|
||||
}
|
||||
return count;
|
||||
}
|
||||
|
||||
// Linear complexity (array traversal)
|
||||
fn arrayTraversal(nums: []i32) i32 {
|
||||
var count: i32 = 0;
|
||||
// The number of iterations is proportional to the array length
|
||||
for (nums) |_| {
|
||||
count += 1;
|
||||
}
|
||||
return count;
|
||||
}
|
||||
|
||||
// Quadratic complexity
|
||||
fn quadratic(n: i32) i32 {
|
||||
var count: i32 = 0;
|
||||
var i: i32 = 0;
|
||||
// The number of iterations is proportional to the square of the input size n
|
||||
while (i < n) : (i += 1) {
|
||||
var j: i32 = 0;
|
||||
while (j < n) : (j += 1) {
|
||||
count += 1;
|
||||
}
|
||||
}
|
||||
return count;
|
||||
}
|
||||
|
||||
// Quadratic complexity (bubble sort)
|
||||
fn bubbleSort(nums: []i32) i32 {
|
||||
var count: i32 = 0; // Counter
|
||||
// Outer loop: the unsorted range is [0, i]
|
||||
var i: i32 = @as(i32, @intCast(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]
|
||||
const tmp = nums[j];
|
||||
nums[j] = nums[j + 1];
|
||||
nums[j + 1] = tmp;
|
||||
count += 3; // Swapping two elements takes 3 elementary operations
|
||||
}
|
||||
}
|
||||
}
|
||||
return count;
|
||||
}
|
||||
|
||||
// Exponential complexity (iterative implementation)
|
||||
fn exponential(n: i32) i32 {
|
||||
var count: i32 = 0;
|
||||
var bas: i32 = 1;
|
||||
var i: i32 = 0;
|
||||
// Each cell divides into two per round, giving the sequence 1, 2, 4, 8, ..., 2^(n-1)
|
||||
while (i < n) : (i += 1) {
|
||||
var j: i32 = 0;
|
||||
while (j < bas) : (j += 1) {
|
||||
count += 1;
|
||||
}
|
||||
bas *= 2;
|
||||
}
|
||||
// count = 1 + 2 + 4 + 8 + .. + 2^(n-1) = 2^n - 1
|
||||
return count;
|
||||
}
|
||||
|
||||
// Exponential complexity (recursive implementation)
|
||||
fn expRecur(n: i32) i32 {
|
||||
if (n == 1) return 1;
|
||||
return expRecur(n - 1) + expRecur(n - 1) + 1;
|
||||
}
|
||||
|
||||
// Logarithmic complexity (iterative implementation)
|
||||
fn logarithmic(n: i32) i32 {
|
||||
var count: i32 = 0;
|
||||
var n_var: i32 = n;
|
||||
while (n_var > 1) : (n_var = @divTrunc(n_var, 2)) {
|
||||
count += 1;
|
||||
}
|
||||
return count;
|
||||
}
|
||||
|
||||
// Logarithmic complexity (recursive implementation)
|
||||
fn logRecur(n: i32) i32 {
|
||||
if (n <= 1) return 0;
|
||||
return logRecur(@divTrunc(n, 2)) + 1;
|
||||
}
|
||||
|
||||
// Linearithmic complexity
|
||||
fn linearLogRecur(n: i32) i32 {
|
||||
if (n <= 1) return 1;
|
||||
var count: i32 = linearLogRecur(@divTrunc(n, 2)) + linearLogRecur(@divTrunc(n, 2));
|
||||
var i: i32 = 0;
|
||||
while (i < n) : (i += 1) {
|
||||
count += 1;
|
||||
}
|
||||
return count;
|
||||
}
|
||||
|
||||
// Factorial complexity (recursive implementation)
|
||||
fn factorialRecur(n: i32) i32 {
|
||||
if (n == 0) return 1;
|
||||
var count: i32 = 0;
|
||||
var i: i32 = 0;
|
||||
// Split one problem into n subproblems
|
||||
while (i < n) : (i += 1) {
|
||||
count += factorialRecur(n - 1);
|
||||
}
|
||||
return count;
|
||||
}
|
||||
|
||||
// Driver code
|
||||
pub fn run() void {
|
||||
// Try different values of n to see how the operation count grows for each complexity
|
||||
const n: i32 = 8;
|
||||
std.debug.print("Input size n = {}\n", .{n});
|
||||
|
||||
var count = constant(n);
|
||||
std.debug.print("Constant-time operation count = {}\n", .{count});
|
||||
|
||||
count = linear(n);
|
||||
std.debug.print("Linear-time operation count = {}\n", .{count});
|
||||
var nums = [_]i32{0} ** n;
|
||||
count = arrayTraversal(&nums);
|
||||
std.debug.print("Linear-time operation count (array traversal) = {}\n", .{count});
|
||||
|
||||
count = quadratic(n);
|
||||
std.debug.print("Quadratic-time operation count = {}\n", .{count});
|
||||
for (&nums, 0..) |*num, i| {
|
||||
num.* = n - @as(i32, @intCast(i)); // [n,n-1,...,2,1]
|
||||
}
|
||||
count = bubbleSort(&nums);
|
||||
std.debug.print("Quadratic-time operation count (bubble sort) = {}\n", .{count});
|
||||
|
||||
count = exponential(n);
|
||||
std.debug.print("Exponential-time operation count (iterative) = {}\n", .{count});
|
||||
count = expRecur(n);
|
||||
std.debug.print("Exponential-time operation count (recursive) = {}\n", .{count});
|
||||
|
||||
count = logarithmic(n);
|
||||
std.debug.print("Logarithmic-time operation count (iterative) = {}\n", .{count});
|
||||
count = logRecur(n);
|
||||
std.debug.print("Logarithmic-time operation count (recursive) = {}\n", .{count});
|
||||
|
||||
count = linearLogRecur(n);
|
||||
std.debug.print("Linearithmic-time operation count (recursive) = {}\n", .{count});
|
||||
|
||||
count = factorialRecur(n);
|
||||
std.debug.print("Factorial-time operation count (recursive) = {}\n", .{count});
|
||||
|
||||
std.debug.print("\n", .{});
|
||||
}
|
||||
|
||||
pub fn main() !void {
|
||||
run();
|
||||
}
|
||||
|
||||
test "time_complexity" {
|
||||
run();
|
||||
}
|
||||
@@ -0,0 +1,53 @@
|
||||
// File: worst_best_time_complexity.zig
|
||||
// Created Time: 2022-12-28
|
||||
// Author: codingonion (coderonion@gmail.com), CreatorMetaSky (creator_meta_sky@163.com)
|
||||
|
||||
const std = @import("std");
|
||||
const utils = @import("utils");
|
||||
|
||||
// Generate an array containing { 1, 2, ..., n } in shuffled order
|
||||
pub fn randomNumbers(comptime n: usize) [n]i32 {
|
||||
var nums: [n]i32 = undefined;
|
||||
// Generate the array nums = { 1, 2, 3, ..., n }
|
||||
for (&nums, 0..) |*num, i| {
|
||||
num.* = @as(i32, @intCast(i)) + 1;
|
||||
}
|
||||
// Randomly shuffle the array elements
|
||||
const rand = std.crypto.random;
|
||||
rand.shuffle(i32, &nums);
|
||||
return nums;
|
||||
}
|
||||
|
||||
// Find the index of the number 1 in array nums
|
||||
pub fn findOne(nums: []i32) i32 {
|
||||
for (nums, 0..) |num, i| {
|
||||
// When 1 is at the start of the array, the best-case time complexity is O(1)
|
||||
// When 1 is at the end of the array, the worst-case time complexity is O(n)
|
||||
if (num == 1) return @intCast(i);
|
||||
}
|
||||
return -1;
|
||||
}
|
||||
|
||||
// Driver code
|
||||
pub fn run() void {
|
||||
var i: i32 = 0;
|
||||
while (i < 10) : (i += 1) {
|
||||
const n: usize = 100;
|
||||
var nums = randomNumbers(n);
|
||||
const index = findOne(&nums);
|
||||
std.debug.print("Shuffled array [1, 2, ..., n] = ", .{});
|
||||
std.debug.print("{}\n", .{utils.fmt.slice(nums)});
|
||||
|
||||
std.debug.print("Index of 1: {}\n", .{index});
|
||||
}
|
||||
|
||||
std.debug.print("\n", .{});
|
||||
}
|
||||
|
||||
pub fn main() !void {
|
||||
run();
|
||||
}
|
||||
|
||||
test "worst_best_time_complexity" {
|
||||
run();
|
||||
}
|
||||
Reference in New Issue
Block a user