Skip to content

Instantly share code, notes, and snippets.


randrew/parts_1_and_2.cpp Secret

Last active Dec 7, 2020
What would you like to do?
aoc 2020 day 7
#include <QDebug>
#include <QFile>
#include <QHash>
#include <QTextStream>
struct InnerBag
QString name;
int count;
void holders(const QMultiHash<QString, QString> &hash, QSet<QString> &results, QString bagName)
auto vals = hash.values(bagName);
for (const auto &val : vals)
holders(hash, results, val);
void expense(const QMultiHash<QString, InnerBag> &hash, int &result, QString bagName, int mul)
auto vals = hash.values(bagName);
for (const auto &val : vals)
result += val.count * mul;
expense(hash, result,, mul * val.count);
int main(int, char **)
QMultiHash<QString, QString> outers;
QMultiHash<QString, InnerBag> inners;
QSet<QString> holdsMyBag;
QFile f("input.txt");;
QTextStream ts(&f);
QString line;
while (!ts.atEnd())
int b1 = line.indexOf("bags");
QString outer = line.left(b1).trimmed();
line = line.right(line.size() - (b1 + 13));
QStringList parts = line.split(',');
if (parts.size() == 1 && == "no other bags.") continue;
for (auto &part : parts)
QString x = part.trimmed();
int n = x.left(x.indexOf(' ')).toInt();
x = x.right(x.size() - x.indexOf(' ') - 1).remove(" bags").remove(" bag").remove('.');
outers.insert(x, outer);
InnerBag ib; = x;
ib.count = n;
inners.insert(outer, ib);
QString myBag = "shiny gold";
holders(outers, holdsMyBag, myBag);
int totalcost = 0;
expense(inners, totalcost, myBag, 1);
qInfo() << holdsMyBag.count();
qInfo() << totalcost;

This comment has been minimized.

Copy link
Owner Author

@randrew randrew commented Dec 7, 2020

35 minutes to create this solution. Didn't want to fuss with fiddly string stuff this time, so I just used a wasteful sledgehammer. Spent about 5 minutes cleaning it up before posting. Here's the non-cleaned-up version:

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment