Quantcast
Channel: Raspberry Pi Forums
Viewing all articles
Browse latest Browse all 5412

Teaching and learning resources • Re: Advent of Code 2024

$
0
0
Finally got day 5 done in C++. Thank you lurk101 I had to look hard and long to work out what you had done. I don't think I would ever have worked out how to use sort.
My version:

Code:

#include <iostream>#include <chrono>#include <fstream>#include <sstream>#include <string>#include <unordered_map>#include <unordered_set>#include <vector>#include <algorithm>const char* fname1 = "data1.txt";const char* fname2 = "data2.txt";int main(){    std::chrono::time_point<std::chrono::system_clock> start,stop;    start = std::chrono::system_clock::now();    std::cout << "Advent of code 2024 day 5" << "\n";    std::ifstream file(fname1);    std::unordered_map<int,std::unordered_set<int>> rules;    // I split the data into two files    if(file)    {        while(!file.eof())        {            // get rules            int i,j;            char c;            file >> i >> c >> j;            rules[i].insert(j);        }    }    file.close();    file.open(fname2);    int part1 = 0;    int part2 = 0;    if(file)    {        while(!file.eof())        {            // get pages            std::string s;            getline(file,s);            std::stringstream ss(s);            std::vector<int> pages;                        while(!ss.eof())            {                int x;                char c;                ss >> x >>  c;                pages.push_back(x);            }            // find if any rule is broken            bool good = true;            int size = pages.size();            for(int i = 0; i < size - 1 ; i++)            {                if(rules[pages[i]].find(pages[i+1]) ==  rules[pages[i]].end())                {                    // no match so rule broken                    good = false;                    break;                }                       }            if(good)                part1 += pages[size/2];            else            {                // inspired by lurk101 code                // sort pages according to rules                std::sort(pages.begin(),pages.end(),                    [&rules](int l, int r){return rules[l].find(r) != rules[l].end();});                part2 += pages[size/2];            }        }    }        std::cout << "Part 1 - " << part1 << "\n";    std::cout << "Part 2 - " << part2 << "\n";    stop = std::chrono::system_clock::now();    std::chrono::duration<double> elapsed = stop - start;    std::cout << "Elapsed time " << elapsed.count() << " seconds" << "\n";    return 0;}

Statistics: Posted by RogerW — Sat Dec 07, 2024 3:31 pm



Viewing all articles
Browse latest Browse all 5412

Trending Articles