advent2015

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

main.cpp (1756B)


      1 #include <iostream>
      2 #include <filesystem>
      3 #include <fstream>
      4 #include <vector>
      5 #include <cstring>
      6 #include <cstdio>
      7 #include <tuple>
      8 #include <algorithm>
      9 
     10 struct Box {
     11     std::string str;
     12     int l{0}, w{0}, h{0};
     13 
     14     Box(const std::string input): str(input) {
     15         std::sscanf(str.c_str(), "%dx%dx%d", &l, &w, &h);
     16     }
     17 
     18     int area() {
     19         return 2*a1() + 2*b1() + 2*c1() + std::min({a1(), b1(), c1()});
     20     }
     21 
     22     int ribbon() {
     23         return std::min({a2(), b2(), c2()}) + l*w*h;
     24     }
     25 
     26     int a1() { return l*w; }
     27     int b1() { return w*h; }
     28     int c1() { return h*l; }
     29     int a2() { return 2*l+2*w; }
     30     int b2() { return 2*w+2*h; }
     31     int c2() { return 2*h+2*l; }
     32 };
     33 
     34 typedef std::vector<Box> Data;
     35 
     36 template<typename T>
     37 T read_file(const std::string &path) {
     38     std::ifstream ifs(path, std::ios::binary);
     39     if (!ifs.is_open()) {
     40         throw std::runtime_error(path+":"+std::strerror(errno));
     41     }
     42     //std::uintmax_t size = std::filesystem::file_size(path);
     43     T buf;
     44     while (1) {
     45         std::string str;
     46         std::getline(ifs, str);
     47         if (!str.empty()) buf.push_back(Box(str));
     48         if (!ifs) break;
     49     }
     50     return buf;
     51 }
     52 
     53 int part1(Data &input) {
     54     int area = 0;
     55     for (auto &b : input) {
     56         area += b.area();
     57     }
     58     return area;
     59 }
     60 int part2(Data &input) {
     61     int ribbon = 0;
     62     for (auto &b : input) {
     63         ribbon += b.ribbon();
     64     }
     65     return ribbon;
     66 }
     67 
     68 int main(int argc, char **argv) {
     69     const std::string fname = argc>1 ? argv[1] : "test1.txt";
     70     std::cout << "AoC 2015 day 02 " << fname << std::endl;
     71     Data input = read_file<Data>(fname);
     72     std::cout << "part1: " << part1(input) << std::endl;
     73     std::cout << "part2: " << part2(input) << std::endl;
     74 
     75     return 0;
     76 }