From 13f7c3a822d00c083d587bec7343f8ad4009380e Mon Sep 17 00:00:00 2001 From: Tomasz Polgrabia Date: Fri, 31 Jan 2025 11:46:43 +0100 Subject: [PATCH] Zig basic project - bipartition. --- current/algorithms/numbers-zig/.gitignore | 2 + current/algorithms/numbers-zig/build.zig | 11 +++++ current/algorithms/numbers-zig/numbers.zig | 57 ++++++++++++++++++++++ 3 files changed, 70 insertions(+) create mode 100644 current/algorithms/numbers-zig/.gitignore create mode 100644 current/algorithms/numbers-zig/build.zig create mode 100644 current/algorithms/numbers-zig/numbers.zig diff --git a/current/algorithms/numbers-zig/.gitignore b/current/algorithms/numbers-zig/.gitignore new file mode 100644 index 0000000..880cd5d --- /dev/null +++ b/current/algorithms/numbers-zig/.gitignore @@ -0,0 +1,2 @@ +zig-out +.zig-cache diff --git a/current/algorithms/numbers-zig/build.zig b/current/algorithms/numbers-zig/build.zig new file mode 100644 index 0000000..652f681 --- /dev/null +++ b/current/algorithms/numbers-zig/build.zig @@ -0,0 +1,11 @@ +const std = @import("std"); + +pub fn build(b: *std.Build) void { + const exe = b.addExecutable(.{ + .name = "numbers", + .root_source_file = b.path("numbers.zig"), + .target = b.host, + + }); + b.installArtifact(exe); +} diff --git a/current/algorithms/numbers-zig/numbers.zig b/current/algorithms/numbers-zig/numbers.zig new file mode 100644 index 0000000..1c5c1a0 --- /dev/null +++ b/current/algorithms/numbers-zig/numbers.zig @@ -0,0 +1,57 @@ +const std = @import("std"); +const print = std.debug.print; +const expect = std.testing.expect; + +test "simple partition #1" { + var gpa = std.heap.GeneralPurposeAllocator(.{}){}; + const allocator = gpa.allocator(); + defer { + _ = gpa.deinit(); + } + + const arr = try allocator.alloc(u64, 3); + arr[0] = 1; + arr[1] = 3; + arr[2] = 5; + defer { + allocator.free(arr); + } + const res = bipartition(arr, 0, @as(u64, arr.len-1), 2); + std.log.warn("Res {}", .{res}); + try expect(res == 1); +} + +pub fn bipartition(arr: []u64, t1: u64, t2: u64, v: u64) u64 { + std.log.warn("Arr called with {}, {}, {}", .{t1, t2, v}); + var x1:u64 = t1; + var x2:u64 = t2; + var x:u64 = undefined; + + if (arr.len <= 0) { + return x1; + } + + if (v < arr[x1]) { + return x1; + } + + if (v >= arr[t2]) { + return t2 + 1; + } + + while (x1 < x2 - 1) { + std.log.warn("Round {},{}", .{t1, t2}); + x = (x1 + x2) / 2; + if (arr[x] < v) { + x1 = x; + } else { + x2 = x; + } + } + + return x2; +} + +pub fn main() !void { + print("Hello World {}!!!\n", .{1}); +}