| 12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667 |
- const std = @import("std");
- const allocator = std.heap.page_allocator;
- fn isRepeatedSequence(sequence: []const u8, prefix: []const u8) !bool {
- if (sequence.len == 0) {
- return true;
- }
- if (!std.mem.startsWith(u8, sequence, prefix)) {
- return false;
- }
- return isRepeatedSequence(sequence[prefix.len..], prefix);
- }
- fn isSillyId(idText: []const u8) !bool {
- for (1..idText.len/2+1) |prefixLen| {
- if (try isRepeatedSequence(idText[prefixLen..], idText[0..prefixLen])) {
- return true;
- }
- }
- return false;
- }
- pub fn main() !void {
- var printBuf: [1024]u8 = undefined;
- const inputFile = try std.fs.cwd().openFile(
- "input.txt",
- .{
- .mode = .read_only,
- },
- );
- defer inputFile.close();
- var inputFileBuffer: [1024]u8 = undefined;
- var inputFileReader = inputFile.reader(&inputFileBuffer);
- const inputFileSize = try inputFileReader.getSize();
- const inputBuffer = try allocator.alloc(u8, inputFileSize);
- try inputFileReader.interface.readSliceAll(inputBuffer);
- var counter:u64 = 0;
- var it = std.mem.tokenizeAny(u8, inputBuffer, ",\n");
- while (it.next()) |token| {
- const dashPos = std.mem.indexOf(u8, token, "-").?;
- const startRangeText = token[0..dashPos];
- const endRangeText = token[dashPos+1..];
- const startRange = try std.fmt.parseInt(u64, startRangeText, 10);
- const endRange = try std.fmt.parseInt(u64, endRangeText, 10);
- for (startRange..endRange+1) |id| {
- const idText = try std.fmt.bufPrint(&printBuf, "{d}", .{id});
- if (try isSillyId(idText)) {
- counter += id;
- }
- }
- }
- try std.fs.File.stdout().writeAll(
- try std.fmt.bufPrint(&printBuf, "{}\n", .{counter}));
- }
|