Skip to content
This repository has been archived by the owner on Aug 27, 2024. It is now read-only.

Commit

Permalink
feat(zig/fib): index stdin with no args
Browse files Browse the repository at this point in the history
Signed-off-by: Roman Volosatovs <[email protected]>
  • Loading branch information
rvolosatovs committed Jul 28, 2022
1 parent b2d32a7 commit 7f288fc
Showing 1 changed file with 26 additions and 4 deletions.
30 changes: 26 additions & 4 deletions Zig/fibonacci/src/main.zig
Original file line number Diff line number Diff line change
Expand Up @@ -5,15 +5,37 @@ fn fibonacci(i: u64) u64 {
return fibonacci(i - 1) + fibonacci(i - 2);
}

fn print_fibonacci(w: anytype, s: []const u8) !void {
const i = try std.fmt.parseUnsigned(u64, s, 10);
try w.print("Fibonacci sequence number at index {d} is {d}\n", .{i, fibonacci(i)});
}

pub fn main() !void {
const alloc: std.mem.Allocator = std.heap.page_allocator;

var args = try std.process.argsAlloc(alloc);
defer alloc.free(args);

const stdout = std.io.getStdOut().writer();
for (args[1..]) |arg| {
const i = try std.fmt.parseUnsigned(u64, arg, 10);
try stdout.print("Fibonacci sequence number at index {d} is {d}\n", .{i, fibonacci(i)});
const stdout = std.io.getStdOut();
defer stdout.close();

const out = stdout.writer();
const indexes = args[1..];
if (indexes.len > 0) {
for (indexes) |arg| {
try print_fibonacci(out, arg);
}
} else {
const stdin = std.io.getStdIn();
defer stdin.close();

try out.print("No arguments specified, please specify Fibonacci sequence index: \n", .{});
var buf: [19]u8 = undefined;
if (try stdin.reader().readUntilDelimiterOrEof(&buf, '\n')) |arg| {
try print_fibonacci(out, arg);
} else {
std.debug.print("failed to read from stdin", .{});
std.process.exit(1);
}
}
}

0 comments on commit 7f288fc

Please sign in to comment.