day2b.zig 1.8 KB

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