launching

This commit is contained in:
Marcius 2024-06-25 21:40:09 +01:00
commit 5a963aeea8
5 changed files with 106 additions and 0 deletions

2
.gitignore vendored Normal file
View file

@ -0,0 +1,2 @@
zig-out
.zig-cache

26
build.zig Normal file
View file

@ -0,0 +1,26 @@
const std = @import("std");
pub fn build(b: *std.Build) void {
const target = b.standardTargetOptions(.{});
const optimize = b.standardOptimizeOption(.{});
const lib = b.addStaticLibrary(.{
.name = "algo-studies",
.root_source_file = b.path("src/root.zig"),
.target = target,
.optimize = optimize,
});
b.installArtifact(lib);
const lib_unit_tests = b.addTest(.{
.root_source_file = b.path("src/root.zig"),
.target = target,
.optimize = optimize,
});
const run_lib_unit_tests = b.addRunArtifact(lib_unit_tests);
const test_step = b.step("test", "Run unit tests");
test_step.dependOn(&run_lib_unit_tests.step);
}

11
build.zig.zon Normal file
View file

@ -0,0 +1,11 @@
.{
.name = "algo-studies",
.version = "0.0.0",
.dependencies = .{},
.paths = .{
"build.zig",
"build.zig.zon",
"src",
},
}

8
src/root.zig Normal file
View file

@ -0,0 +1,8 @@
const std = @import("std");
const testing = std.testing;
test {
_ = BinarySearch;
}
pub const BinarySearch = @import("search/binary-search.zig");

View file

@ -0,0 +1,59 @@
const std = @import("std");
const testing = std.testing;
const assert = std.debug.assert;
const BinarySearchOptions = struct {
//not using recursion by default
rercusive: bool = false,
};
pub fn search(array: anytype, target: anytype, options: BinarySearchOptions) @TypeOf(array[0]) {
assertNumber(@TypeOf(array));
if (options.rercusive) {
@panic("Not implemented yet");
}
var left = 0;
var right = array.len - 1;
while (left < right) {
const mid: usize = std.math.floor((left + right) / 2);
if (array[mid] == target) {
return target;
}
if (array[mid] < target) {
left = mid;
}
if (array[mid] > target) {
right = mid;
}
}
return 0;
}
pub fn searchRecursive(comptime T: type, array: []T, target: T) i8 {
_ = target;
_ = array;
@panic("Recursive search not implemented");
}
fn recursion(array: []i8) []i8 {
_ = array;
}
fn assertNumber(comptime T: type) void {
switch (@typeInfo(T)) {
.Array => |info| switch (@typeInfo(info.child)) {
.Float, .ComptimeFloat, .ComptimeInt, .Int => return,
else => @compileError("binary search not implemented for " ++ @typeName(T)),
},
else => @compileError("binary search exepects an array instead of " ++ @typeName(T)),
}
std.math.sqrt(T);
}
test "test binary search" {
const array = [_]i8{ 1, 2, 3, 4, 6, 7, 8, 9, 10, 12 };
try testing.expectEqual(null, search(array, 5, .{}));
try testing.expectEqual(2, search(array, 5, .{}));
}