my solutions to advent of code
aoc advent-of-code
at main 1.6 kB view raw
1const std = @import("std"); 2 3const State = struct { turn: i32, zeroes: u32 }; 4 5pub fn main() !void { 6 const allocator = std.heap.page_allocator; 7 8 const input_raw = @embedFile("./input.txt"); 9 const input_str = std.mem.trim(u8, input_raw, "\t\r\n"); 10 var turns_str = std.mem.splitScalar(u8, input_str, '\n'); 11 12 const turns_len = 13 std.mem.count(u8, input_str, "\n") + 1; 14 const turns = try allocator.alloc(i32, turns_len); 15 defer allocator.free(turns); 16 17 var i: u32 = 0; 18 while (turns_str.next()) |turn_str| { 19 const mult: i32 = if (turn_str[0] == 'L') -1 else 1; 20 turns[i] = try std.fmt.parseInt(i32, turn_str[1..], 10) * mult; 21 i += 1; 22 } 23 24 var part_1 = State{ .turn = 50, .zeroes = 0 }; 25 for (turns) |turn| { 26 part_1.turn = @mod(part_1.turn + turn, 100); 27 part_1.zeroes += @intFromBool(part_1.turn == 0); 28 } 29 std.debug.print("Part 1: {}\n", .{part_1.zeroes}); 30 31 var part_2 = State{ .turn = 50, .zeroes = 0 }; 32 for (turns) |turn| { 33 const raw_turn: i32 = part_2.turn + turn; 34 // if it is below zero before being moduloed and the original number itself wasn't zero it means that it did touch zero but the division thing wouldn't count it, so we give this extra support. 35 // of course, there is no need to deal with a negative to positive situation because the acc.turn will never be negative!!! 36 part_2.zeroes += @abs(raw_turn) / 100 + @intFromBool(part_2.turn != 0 and raw_turn <= 0); 37 part_2.turn = @mod(raw_turn, 100); 38 } 39 std.debug.print("Part 2: {}\n", .{part_2.zeroes}); 40}