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

feat(zig/fib): index stdin with no args #28

Merged
merged 1 commit into from
Aug 1, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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);
}
}
}
2 changes: 1 addition & 1 deletion flake.nix
Original file line number Diff line number Diff line change
Expand Up @@ -159,7 +159,7 @@

fibonacci-zig-wasm = final.stdenv.mkDerivation {
pname = "fibonacci";
version = "0.2.0";
bstrie marked this conversation as resolved.
Show resolved Hide resolved
version = "0.3.0";

src = "${self}/Zig/fibonacci";

Expand Down