advent2015

advent of code 2015 (c++)
git clone git://bsandro.tech/advent2015
Log | Files | Refs

main.cpp (1266B)


      1 #include <iostream>
      2 #include <filesystem>
      3 #include <fstream>
      4 #include <vector>
      5 #include <cstring>
      6 
      7 typedef std::vector<char> Data;
      8 
      9 template<typename T>
     10 T read_file(const std::string &path) {
     11     std::ifstream ifs(path, std::ios::binary);
     12     if (!ifs.is_open()) {
     13         throw std::runtime_error(path+":"+std::strerror(errno));
     14     }
     15     std::uintmax_t size = std::filesystem::file_size(path);
     16     T buf(size);
     17     if (!ifs.read((char *)buf.data(), buf.size())) {
     18         throw std::runtime_error(path+":"+std::strerror(errno));
     19     }
     20     return buf;
     21 }
     22 
     23 int part1(Data &input) {
     24     int ret = 0;
     25     for (auto &f : input) {
     26         if (f=='(') ++ret;
     27         else if (f==')') --ret;
     28     }
     29     return ret;
     30 }
     31 int part2(Data &input) {
     32     int ret = 0;
     33     for (int i=0; i<(int)input.size(); ++i) {
     34         char f = input[i];
     35         if (f=='(') ++ret;
     36         else if (f==')') --ret;
     37         if (ret<0) return i+1;
     38     }
     39     return 0;
     40 }
     41 
     42 int main(int argc, char **argv) {
     43     const std::string fname = argc>1 ? argv[1] : "test1.txt";
     44     std::cout << "AoC 2015 day 01 " << fname << std::endl;
     45 
     46     Data input = read_file<Data>(fname);
     47 
     48     std::cout << "part1: " << part1(input) << std::endl;
     49     std::cout << "part2: " << part2(input) << std::endl;
     50 
     51     return 0;
     52 }