day1b.zig 1.5 KB

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