Created
December 1, 2023 21:40
-
-
Save andrewrk/c1c97aaa574095c0088e9b387f32457c to your computer and use it in GitHub Desktop.
advent of code 2023 day 1 part 1 in zig
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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