day1a.zig 1.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  1. const std = @import("std");
  2. const allocator = std.heap.page_allocator;
  3. const Dial = struct {
  4. v: i32 = 50,
  5. fn Left(self: *Dial, count: u32) void {
  6. self.v -= @intCast(count % 100);
  7. if (self.v < 0) {
  8. self.v += 100;
  9. }
  10. }
  11. fn Right(self: *Dial, count: u32) void {
  12. self.v += @intCast(count % 100);
  13. if (self.v >= 100) {
  14. self.v -= 100;
  15. }
  16. }
  17. };
  18. pub fn main() !void {
  19. const inputFile = try std.fs.cwd().openFile(
  20. "input.txt",
  21. .{
  22. .mode = .read_only,
  23. },
  24. );
  25. defer inputFile.close();
  26. var inputFileBuffer: [1024]u8 = undefined;
  27. var inputFileReader = inputFile.reader(&inputFileBuffer);
  28. const inputFileSize = try inputFileReader.getSize();
  29. var printBuf: [1024]u8 = undefined;
  30. const inputBuffer = try allocator.alloc(u8, inputFileSize);
  31. try inputFileReader.interface.readSliceAll(inputBuffer);
  32. var dial: Dial = .{};
  33. var zeroCount: i32 = 0;
  34. var it = std.mem.tokenizeScalar(u8, inputBuffer, '\n');
  35. while (it.next()) |token| {
  36. const direction = token[0];
  37. const count = try std.fmt.parseInt(u32, token[1..], 10);
  38. if (direction == 'L') {
  39. dial.Left(count);
  40. } else {
  41. dial.Right(count);
  42. }
  43. if (dial.v == 0) {
  44. zeroCount += 1;
  45. }
  46. }
  47. try std.fs.File.stdout().writeAll(try std.fmt.bufPrint(&printBuf, "{d}\n", .{zeroCount}));
  48. }