day2a.zig 1.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748
  1. const std = @import("std");
  2. const allocator = std.heap.page_allocator;
  3. pub fn main() !void {
  4. var printBuf: [1024]u8 = undefined;
  5. const inputFile = try std.fs.cwd().openFile(
  6. "input.txt",
  7. .{
  8. .mode = .read_only,
  9. },
  10. );
  11. defer inputFile.close();
  12. var inputFileBuffer: [1024]u8 = undefined;
  13. var inputFileReader = inputFile.reader(&inputFileBuffer);
  14. const inputFileSize = try inputFileReader.getSize();
  15. const inputBuffer = try allocator.alloc(u8, inputFileSize);
  16. try inputFileReader.interface.readSliceAll(inputBuffer);
  17. var counter:u64 = 0;
  18. var it = std.mem.tokenizeAny(u8, inputBuffer, ",\n");
  19. while (it.next()) |token| {
  20. const dashPos = std.mem.indexOf(u8, token, "-").?;
  21. const startRangeText = token[0..dashPos];
  22. const endRangeText = token[dashPos+1..];
  23. const startRange = try std.fmt.parseInt(u64, startRangeText, 10);
  24. const endRange = try std.fmt.parseInt(u64, endRangeText, 10);
  25. for (startRange..endRange+1) |id| {
  26. const idText = try std.fmt.bufPrint(&printBuf, "{d}", .{id});
  27. const halfLen = idText.len/2;
  28. const firstHalfText = idText[0..halfLen];
  29. const secondHalfText = idText[halfLen..];
  30. if (std.mem.eql(u8, firstHalfText, secondHalfText)) {
  31. counter += id;
  32. }
  33. }
  34. }
  35. try std.fs.File.stdout().writeAll(
  36. try std.fmt.bufPrint(&printBuf, "{}\n", .{counter}));
  37. }