Hacker News new | ask | show | jobs
by Zambyte 248 days ago
Regarding iteration, a simple solution without reaching for while loops is to iterate on a range and operate relative to the length.

    const a = [_]u8{ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };

    // 2 4 6 8 10
    for (a[0 .. a.len / 2], 0..) |_, i| {
        std.debug.print("{} ", .{a[i * 2 + 1]});
    }

    std.debug.print("\n", .{});

    // 1 3 5 7 9 
    for (a[0 .. (a.len + 1) / 2], 0..) |_, i| {
        std.debug.print("{} ", .{a[i * 2]});
    }

    std.debug.print("\n", .{});

    // 10 9 8 7 6 5 4 3 2 1
    for (0..a.len) |i| {
        std.debug.print("{} ", .{a[a.len - i - 1]});
    }