commit caf46e3

Artur Manuel  ·  2026-05-20 21:23:50 +0000 UTC
parent a733eec
zig: add collatz conjecture for zig
3 files changed,  +65, -0
+23, -0
 1@@ -0,0 +1,23 @@
 2+const std = @import("std");
 3+
 4+pub fn build(b: *std.Build) void {
 5+    const target = b.standardTargetOptions(.{});
 6+    const optimize = b.standardOptimizeOption(.{});
 7+    const exe = b.addExecutable(.{
 8+        .name = "rosetta-collatz",
 9+        .root_module = b.createModule(.{
10+            .root_source_file = b.path("src/main.zig"),
11+            .target = target,
12+            .optimize = optimize,
13+        }),
14+    });
15+
16+    b.installArtifact(exe);
17+    const run_step = b.step("run", "Run the app");
18+    const run_cmd = b.addRunArtifact(exe);
19+    run_step.dependOn(&run_cmd.step);
20+    run_cmd.step.dependOn(b.getInstallStep());
21+    if (b.args) |args| {
22+        run_cmd.addArgs(args);
23+    }
24+}
+7, -0
1@@ -0,0 +1,7 @@
2+.{
3+    .name = .rosetta_collatz,
4+    .fingerprint = 0xbe90948eaeae8406,
5+    .version = "2026.5.1",
6+    .minimum_zig_version = "0.16.0",
7+    .paths = .{""},
8+}
+35, -0
 1@@ -0,0 +1,35 @@
 2+const std = @import("std");
 3+
 4+const Io = std.Io;
 5+
 6+fn collatz(n: u32) u32 {
 7+    if (n % 2 == 0) {
 8+        return @divFloor(n, 2);
 9+    }
10+    return 3 * n + 1;
11+}
12+
13+fn collatzSequence(gpa: std.mem.Allocator, n: u32) ![]u8 {
14+    var result = std.ArrayList(u8).empty;
15+    var i = collatz(n);
16+    while (i != 1) {
17+        try result.print(gpa, "{d}, ", .{i});
18+        i = collatz(i);
19+    }
20+    try result.appendSlice(gpa, "1");
21+    return try result.toOwnedSlice(gpa);
22+}
23+
24+pub fn main(init: std.process.Init) !void {
25+    const gpa = init.arena.allocator();
26+    var buffer: [16384]u8 = undefined;
27+    var stdout = Io.File.stdout().writer(init.io, &buffer);
28+    var i: u32 = 1;
29+    while (i < 10001) {
30+        const sequence = try collatzSequence(gpa, i);
31+        try stdout.interface.print("{d}: {s}\n", .{ i, sequence });
32+        i += 1;
33+    }
34+    try stdout.interface.flush();
35+    _ = init.arena.reset(.free_all);
36+}