PR3-Klausur-Uben/ZIG/u1.zig

80 lines
2.0 KiB
Zig

const std = @import("std");
pub fn main() !void {
const reader = std.io.getStdIn().reader();
const writer = std.io.getStdOut().writer();
//? Fibonacci calculation
try writer.print("Fib Calc: \n", .{});
const resFib: i8 = calcFib(5);
std.debug.print("Fib Res: {d} \n", .{resFib});
try writer.print("\n", .{});
//? Zahlen raten
try writer.print("Zahlen raten: \n", .{});
try zahlenRaten(reader, writer, 50);
}
pub fn calcFib(n: i8) i8 {
if (n == 0) {
return 1;
}
return n * calcFib(n - 1);
}
pub fn zahlenRaten(reader: anytype, writer: anytype, upperLimit: i8) !void {
const rand = std.crypto.random;
const target: i64 = rand.intRangeLessThan(i64, 0, upperLimit);
var counter: i8 = 0;
while (true) {
counter += 1;
const guess = try getOneIntInput(reader, writer);
if (guess < target) {
try writer.print("{d} is too small \n", .{guess});
continue;
}
if (guess > target) {
try writer.print("{d} is too big \n", .{guess});
continue;
}
try writer.print("{d} is the correct guess!\nIt took you {d} tries.\n", .{guess, counter});
break;
}
}
pub fn getOneIntInput(reader: anytype, writer: anytype) !i8 {
var buff: [256]u8 = undefined;
while(true) {
try writer.print("> ", .{});
const amountBytesRead = try reader.read(&buff);
const uncleanData: []u8 = buff[0..(amountBytesRead - 1)];
const data = std.mem.trimRight(u8, uncleanData, "\r\n");
const guess = std.fmt.parseInt(i8, data, 10) catch |err|{
switch (err) {
error.InvalidCharacter => {
try writer.print("Invald character: {s}, try again! \n", .{data});
},
error.Overflow => {
try writer.print("Overflow: {s}, try again! \n", .{data});
}
}
try writer.print("\n", .{});
continue;
};
return guess;
}
}