Skip to content

Instantly share code, notes, and snippets.

@perky
Last active December 12, 2023 16:48
Show Gist options
  • Save perky/3c62725d9f0456300fcf2a41f2ed7f02 to your computer and use it in GitHub Desktop.
Save perky/3c62725d9f0456300fcf2a41f2ed7f02 to your computer and use it in GitHub Desktop.
Advent of Code 2023
const std = @import("std");
const c = @cImport({
@cInclude("raylib.h");
});
const word_numbers = [_][]const u8{
"one",
"two",
"three",
"four",
"five",
"six",
"seven",
"eight",
"nine"
};
pub fn main() !void {
c.InitWindow(1080, 720, "Advent of Code 2023");
c.SetTargetFPS(60);
const allocator = std.heap.c_allocator;
const answer = try processPuzzleInput(allocator);
const answer_text = try std.fmt.allocPrintZ(allocator, "The answer is: {d}", .{ answer });
while (!c.WindowShouldClose())
{
c.BeginDrawing();
defer c.EndDrawing();
c.ClearBackground(c.RED);
c.DrawText(answer_text, 190, 200, 20, c.GREEN);
}
c.CloseWindow();
}
fn processLine(line: []const u8, bReverse: bool) !i32 {
if (line.len == 0) {
return error.InvalidLine;
}
for (0..line.len) |i| {
const char_i = if (bReverse) (line.len - i - 1) else i;
const line_slice = line[char_i..];
for (word_numbers, 0..) |word, word_i| {
if (std.mem.startsWith(u8, line_slice, word)) {
return @intCast(i32, word_i + 1);
}
}
if (std.ascii.isDigit(line[char_i])) {
return (line[char_i] - '0');
}
}
return error.InvalidLine;
}
fn processPuzzleInput(allocator: std.mem.Allocator) !i32 {
const puzzle_input = try std.fs.cwd().readFileAlloc(
allocator,
"puzzle_input/day01.txt",
1024 * 1024
);
var sum: i32 = 0;
var line_iter = std.mem.splitScalar(u8, puzzle_input, '\n');
while (line_iter.next()) |line| {
const first_digit: i32 = try processLine(line, false);
const last_digit: i32 = try processLine(line, true);
const number: i32 = (first_digit * 10) + last_digit;
sum = sum + number;
}
return sum;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment