Skip to content

Instantly share code, notes, and snippets.

@andrewrk
Created December 1, 2023 21:40
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save andrewrk/c1c97aaa574095c0088e9b387f32457c to your computer and use it in GitHub Desktop.
Save andrewrk/c1c97aaa574095c0088e9b387f32457c to your computer and use it in GitHub Desktop.
advent of code 2023 day 1 part 1 in zig
const std = @import("std");
const example =
\\1abc2
\\pqr3stu8vwx
\\a1b2c3d4e5f
\\treb7uchet
;
pub fn main() !void {
var it = std.mem.splitScalar(u8, example, '\n');
var sum: u32 = 0;
while (it.next()) |line| {
var first: ?u8 = null;
var last: ?u8 = null;
for (line) |byte| {
if (isDigit(byte)) {
if (first == null) first = byte;
last = byte;
}
}
const n = (@as(u32, first.?) - '0') * 10 + (last.? - '0');
sum += n;
}
try std.io.getStdOut().writer().print("{d}\n", .{sum});
}
fn isDigit(byte: u8) bool {
return switch (byte) {
'0'...'9' => true,
else => false,
};
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment