Skip to content

Commit 725cef8

Browse files
committed
feat: add more examples
1 parent 4ed0e4e commit 725cef8

File tree

6 files changed

+234
-38
lines changed

6 files changed

+234
-38
lines changed
Lines changed: 81 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,81 @@
1+
// Source: https://qsantos.fr/2024/01/04/dynamic-programming-is-not-black-magic/
2+
const std = @import("std");
3+
const time = std.time;
4+
5+
const Timer = time.Timer;
6+
7+
var gpa = std.heap.GeneralPurposeAllocator(.{}){};
8+
const allocator = gpa.allocator();
9+
10+
var cache = std.AutoHashMap(u128, u128).init(allocator);
11+
12+
13+
fn fibonacciRecursiveMemoized(comptime T: type, n: T) T {
14+
if (n == 0) {
15+
cache.put(0, 0) catch unreachable;
16+
return 0;
17+
}
18+
if (n == 1) {
19+
cache.put(1, 1) catch unreachable;
20+
return 1;
21+
}
22+
const n_2 = cache.get(n - 2) orelse fibonacciRecursiveMemoized(T, n - 2);
23+
const n_1 = cache.get(n - 1) orelse fibonacciRecursiveMemoized(T, n - 1);
24+
if (!cache.contains(n - 2)) cache.put(n - 2, n_2) catch unreachable;
25+
if (!cache.contains(n - 1)) cache.put(n - 1, n_1) catch unreachable;
26+
return n_2 + n_1;
27+
}
28+
29+
fn fibonacciRecursive(comptime T: type, n: T) T {
30+
if (n == 0) return 0;
31+
if (n == 1) return 1;
32+
return fibonacciRecursive(T, n - 2) + fibonacciRecursive(T, n - 1);
33+
}
34+
35+
fn fibonacciDynamicProgramming(comptime T: type, n: T) T {
36+
if (n == 0) return 0;
37+
var previous_previous: T = 0;
38+
var previous: T = 1;
39+
for (0..@intCast(n - 1)) |_| {
40+
const current = previous_previous + previous;
41+
previous_previous = previous;
42+
previous = current;
43+
}
44+
return previous;
45+
}
46+
47+
pub fn main() !void {
48+
const input_values = [_]u32{ 1, 2, 3, 8, 12, 30, 40, 42, 43, 44 };
49+
50+
for (input_values) |input| {
51+
std.debug.print("\n\n>>> Input \x1B[33m{d}\x1B[0m → fibonacci", .{ input });
52+
53+
var timer = Timer.start() catch {
54+
unreachable;
55+
};
56+
const result_dp = fibonacciDynamicProgramming(u128, input);
57+
var elapsed: f64 = @floatFromInt(timer.read()) ;
58+
var dur: u64 = @intFromFloat(elapsed / time.ns_per_ms);
59+
std.debug.print("\n\x1B[31mDynamic Programming:\n{d: >4} [{d} ms]", .{ result_dp, dur });
60+
61+
62+
timer = Timer.start() catch {
63+
unreachable;
64+
};
65+
const result_recur_memo = fibonacciRecursiveMemoized(u128, input);
66+
elapsed = @floatFromInt(timer.read()) ;
67+
dur = @intFromFloat(elapsed / time.ns_per_ms);
68+
std.debug.print("\n\x1B[32mRecursive (Memoized):\n{d: >4} [{d} ms]", .{ result_recur_memo, dur });
69+
70+
71+
timer = Timer.start() catch {
72+
unreachable;
73+
};
74+
const result_recur = fibonacciRecursive(u128, input);
75+
elapsed = @floatFromInt(timer.read()) ;
76+
dur = @intFromFloat(elapsed / time.ns_per_ms);
77+
std.debug.print("\n\x1B[34mRecursive:\n{d: >4} [{d} ms]", .{ result_recur, dur });
78+
79+
std.debug.print("\x1B[0m", .{});
80+
}
81+
}

src/examples/comp-partial.zig

Lines changed: 0 additions & 38 deletions
This file was deleted.
Lines changed: 42 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,42 @@
1+
/// Sources:
2+
/// https://zig.news/kristoff/easy-interfaces-with-zig-0100-2hc5
3+
/// https://www.youtube.com/watch?v=AHc4x1uXBQE
4+
/// https://ziggit.dev/t/polymorphism-with-zig-0-10-0/463/10
5+
6+
const std = @import("std");
7+
8+
const Shape = union(enum) {
9+
circle: Circle,
10+
rectangle: Rectangle,
11+
12+
pub fn area(self: *Shape) f32 {
13+
switch(self.*) {
14+
inline else => |*kind| kind.area(),
15+
}
16+
}
17+
};
18+
19+
const Circle = struct {
20+
radius: f32 = 1,
21+
22+
pub fn area(self: Circle) f32 {
23+
return 2.0 * std.math.pi * self.radius;
24+
}
25+
};
26+
27+
const Rectangle = struct {
28+
width: f32 = 1,
29+
height: f32 = 1,
30+
31+
pub fn area(self: Rectangle) f32 {
32+
return self.width * self.height;
33+
}
34+
};
35+
36+
pub fn main() !void {
37+
const circ = Circle{ .radius = 12 };
38+
std.debug.print("\nCircle area: {d:.3}", .{ circ.area() });
39+
40+
const rect = Rectangle{ .width = 4, .height = 3 };
41+
std.debug.print("\nRectangle area: {d:.3}", .{ rect.area() });
42+
}
Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,27 @@
1+
const std = @import("std");
2+
const f = @import("shared").functional;
3+
4+
fn addX(comptime T: type, comptime x: T, v: T) T {
5+
return v + x;
6+
}
7+
8+
fn subX(comptime T: type, comptime x: T, v: T) T {
9+
return v - x;
10+
}
11+
12+
fn mulX(comptime T: type, comptime x: T, v: T) T {
13+
return v * x;
14+
}
15+
16+
pub fn main() !void {
17+
const combined = f.comp(u32, .{
18+
f.partial(u32, addX, 5),
19+
f.partial(u32, mulX, 10),
20+
f.partial(u32, subX, 3),
21+
f.partial(u32, mulX, 2),
22+
});
23+
std.debug.print("\nFunction Composition", .{});
24+
for (1..10) |i| {
25+
std.debug.print("\n((({d} + 5) * 10) - 3) * 2: {d}", .{ i, combined(@intCast(i)) });
26+
}
27+
}
Lines changed: 36 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,36 @@
1+
const std = @import("std");
2+
const f = @import("shared").functional;
3+
4+
fn addX(comptime T: type, comptime x: T, v: T) T {
5+
return v + x;
6+
}
7+
8+
fn multX(comptime T: type, comptime x: T, v: T) T {
9+
return v * x;
10+
}
11+
12+
fn multXAddY(comptime T: type, comptime x: T, comptime y: T, v: T) T {
13+
return (x * v) + y;
14+
}
15+
16+
pub fn main() !void {
17+
std.debug.print("Partial Function Application", .{});
18+
19+
std.debug.print("\nCreate an add8 function:", .{});
20+
const add8 = f.partial(u8, addX, 8);
21+
for (0..3) |i| {
22+
std.debug.print("\n {d} + 8 = {d}", .{ i, add8(@intCast(i)) });
23+
}
24+
25+
std.debug.print("\nCreate a multiply with 5 function:", .{});
26+
const mult5 = f.partial(u8, multX, 5);
27+
for (1..6) |i| {
28+
std.debug.print("\n {d} x 5 = {d}", .{ i, mult5(@intCast(i)) });
29+
}
30+
31+
std.debug.print("\nCreate a function which calculates 5 * x + 2:", .{});
32+
const mult2add5 = f.partial2(u8, multXAddY, 2, 5);
33+
for (0..10) |i| {
34+
std.debug.print("\n 2 * {d} + 5 = {d}", .{ i, mult2add5(@intCast(i)) });
35+
}
36+
}

src/examples/io/streams.zig

Lines changed: 48 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,48 @@
1+
const std = @import("std");
2+
3+
var gpa = std.heap.GeneralPurposeAllocator(.{}){};
4+
const allocator = gpa.allocator();
5+
6+
const OscArgument = packed struct {
7+
tag_type: u8 = 'i',
8+
value: i32 = undefined,
9+
10+
pub fn format(
11+
self: OscArgument,
12+
writer: *std.Io.Writer,
13+
) std.Io.Writer.Error!void {
14+
try writer.print("\nOSC Argument:\n - {c} - {d}", .{
15+
self.tag_type,
16+
self.value,
17+
});
18+
}
19+
};
20+
21+
pub fn main() !void {
22+
const buffer: []u8 = try allocator.alloc(u8, 100);
23+
var stream = std.io.fixedBufferStream(buffer);
24+
var writer = stream.writer();
25+
try writer.writeInt(i32, 1337, .big);
26+
try writer.writeInt(i32, 128, .big);
27+
try writer.writeStruct(OscArgument{
28+
.tag_type = 'i',
29+
.value = 1337,
30+
});
31+
32+
const written = stream.getWritten();
33+
std.debug.print("Buffer Written:\n > {any}", .{written});
34+
35+
var out_stream = std.io.fixedBufferStream(written);
36+
var reader = out_stream.reader();
37+
38+
var out = try reader.readInt(i32, .big);
39+
std.debug.print("\n\nRead Integer:\n > {any}", .{out_stream.buffer});
40+
std.debug.print("\n > {d}", .{out});
41+
42+
out = try reader.readInt(i32, .big);
43+
std.debug.print("\n\nRead Integer:\n > {any}", .{out_stream.buffer});
44+
std.debug.print("\n > {d}", .{out});
45+
46+
const out_struct = try reader.readStruct(OscArgument);
47+
std.debug.print("\n{f}", .{out_struct});
48+
}

0 commit comments

Comments
 (0)