Skip to content

Instantly share code, notes, and snippets.

@maxsei
Created December 4, 2023 15:41
Show Gist options
  • Select an option

  • Save maxsei/39cd6974faf254d047991f4153ecf071 to your computer and use it in GitHub Desktop.

Select an option

Save maxsei/39cd6974faf254d047991f4153ecf071 to your computer and use it in GitHub Desktop.
throwaway aoc day one part 2 using zig because I suck at racket
const std = @import("std");
const io = std.io;
fn getmatch(x: []u8) usize {
if (std.mem.startsWith(u8, x, "1")) {
return 1;
} else if (std.mem.startsWith(u8, x, "2")) {
return 2;
} else if (std.mem.startsWith(u8, x, "3")) {
return 3;
} else if (std.mem.startsWith(u8, x, "4")) {
return 4;
} else if (std.mem.startsWith(u8, x, "5")) {
return 5;
} else if (std.mem.startsWith(u8, x, "6")) {
return 6;
} else if (std.mem.startsWith(u8, x, "7")) {
return 7;
} else if (std.mem.startsWith(u8, x, "8")) {
return 8;
} else if (std.mem.startsWith(u8, x, "9")) {
return 9;
} else if (std.mem.startsWith(u8, x, "one")) {
return 1;
} else if (std.mem.startsWith(u8, x, "two")) {
return 2;
} else if (std.mem.startsWith(u8, x, "three")) {
return 3;
} else if (std.mem.startsWith(u8, x, "four")) {
return 4;
} else if (std.mem.startsWith(u8, x, "five")) {
return 5;
} else if (std.mem.startsWith(u8, x, "six")) {
return 6;
} else if (std.mem.startsWith(u8, x, "seven")) {
return 7;
} else if (std.mem.startsWith(u8, x, "eight")) {
return 8;
} else if (std.mem.startsWith(u8, x, "nine")) {
return 9;
} else {
return 0;
}
}
pub fn main() !void {
var file = try std.fs.cwd().openFile("../inputs/01.txt", .{});
defer file.close();
var buf_reader = io.bufferedReader(file.reader());
var in_stream = buf_reader.reader();
var buf: [1024]u8 = undefined;
var ret: usize = 0;
while (try in_stream.readUntilDelimiterOrEof(&buf, '\n')) |line| {
const first = blk: {
var i: usize = 0;
while (i < line.len) {
const x = getmatch(line[i..]);
if (x > 0) {
break :blk x;
}
i += 1;
}
@panic("failed to get any tokens");
};
const last = blk: {
var i: usize = line.len - 1;
while (i >= 0) {
const x = getmatch(line[i..]);
if (x > 0) {
break :blk x;
}
i -= 1;
}
@panic("failed to get any tokens");
};
// std.debug.print("{d}{d}\n", .{ first, last });
ret += 10 * first + last;
}
std.debug.print("{d}\n", .{ret});
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment