advent-of-code

Solutions for Advent of Code.
git clone git://git.amin.space/advent-of-code.git
Log | Files | Refs | LICENSE

day_01_1.zig (1403B)


      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 total_sum(input01);
     14     debug.assert(result == 599);
     15     debug.warn("01-1: {}\n", result);
     16 }
     17 
     18 fn total_sum(input: []const u8) !i32 {
     19     var sum: i32 = 0;
     20     var index: usize = 0;
     21     while (index < input.len) {
     22         var e = index;
     23         while (input[e] != '\n') {
     24             e += 1;
     25         }
     26         debug.assert('\n' == input[e]);
     27 
     28         var num = try fmt.parseInt(i32, input[index..e], 10);
     29         sum += num;
     30         index = e + 1;
     31     }
     32     return sum;
     33 }
     34 
     35 test "total_sum" {
     36     const s: []const u8 = "-2\n-3\n+4\n-15\n-15\n+18\n-7\n+11\n-16\n-134\n+200\n";
     37     debug.assert(41 == try total_sum(s));
     38 }
     39 
     40 fn get_file_contents(allocator: *mem.Allocator, file_name: []const u8) ![]u8 {
     41     var file = try os.File.openRead(file_name);
     42     defer file.close();
     43 
     44     const file_size = try file.getEndPos();
     45 
     46     var file_in_stream = io.FileInStream.init(file);
     47     var buf_stream = io.BufferedInStream(io.FileInStream.Error).init(&file_in_stream.stream);
     48     const st = &buf_stream.stream;
     49     return try st.readAllAlloc(allocator, 2 * file_size);
     50 }