day_01_2.zig (2226B)
1 const std = @import("std"); 2 const debug = std.debug; 3 const fmt = std.fmt; 4 const io = std.io; 5 const mem = std.mem; 6 const os = std.os; 7 8 pub fn main() !void { 9 var allocator = &std.heap.DirectAllocator.init().allocator; 10 var input01 = try get_file_contents(allocator, "input_01.txt"); 11 defer allocator.free(input01); 12 13 var result = try first_visited_twice(input01); 14 debug.assert(result == 81204); 15 debug.warn("01-2: {}\n", result); 16 } 17 18 fn first_visited_twice(input: []const u8) !i32 { 19 var sum: i32 = 0; 20 var index: usize = 0; 21 22 const visited_magnitude: usize = 1000000; 23 const visited_size: usize = (visited_magnitude * 2) + 1; 24 // [ -visited_magnitude, ..., -3, -2, -1, 0, 1, 2, 3, ..., visited_magnitude ] 25 var visited = []bool{false} ** visited_size; 26 27 //debug.warn("{} ", sum); 28 while (true) { 29 var visited_index = @intCast(usize, @intCast(i32, visited_magnitude) + sum); 30 debug.assert(visited_index >= 0); 31 if (visited[visited_index] == true) { 32 return sum; 33 } else { 34 visited[visited_index] = true; 35 } 36 37 var e = index; 38 while (input[e] != '\n') { 39 e += 1; 40 } 41 debug.assert('\n' == input[e]); 42 43 var num = try fmt.parseInt(i32, input[index..e], 10); 44 sum += num; 45 //debug.warn("+ {}\n", num); 46 //debug.warn("{} ", sum); 47 index = (e + 1) % input.len; 48 } 49 debug.warn("\n---\n"); 50 return sum; 51 } 52 53 test "first_visited_twice" { 54 debug.assert(0 == try first_visited_twice("+1\n-1\n")); 55 debug.assert(10 == try first_visited_twice("+3\n+3\n+4\n-2\n-4\n")); 56 debug.assert(5 == try first_visited_twice("-6\n+3\n+8\n+5\n-6\n")); 57 debug.assert(14 == try first_visited_twice("+7\n+7\n-2\n-7\n-4\n")); 58 } 59 60 fn get_file_contents(allocator: *mem.Allocator, file_name: []const u8) ![]u8 { 61 var file = try os.File.openRead(file_name); 62 defer file.close(); 63 64 const file_size = try file.getEndPos(); 65 66 var file_in_stream = io.FileInStream.init(file); 67 var buf_stream = io.BufferedInStream(io.FileInStream.Error).init(&file_in_stream.stream); 68 const st = &buf_stream.stream; 69 return try st.readAllAlloc(allocator, 2 * file_size); 70 }