Skip to content

Instantly share code, notes, and snippets.

@randrew

randrew/parts_1_and_2.cpp Secret

Last active Dec 7, 2020
Embed
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)
{
results.insert(val);
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, val.name, mul * val.count);
}
}
int main(int, char **)
{
QMultiHash<QString, QString> outers;
QMultiHash<QString, InnerBag> inners;
QSet<QString> holdsMyBag;
QFile f("input.txt");
f.open(QIODevice::ReadOnly);
QTextStream ts(&f);
QString line;
while (!ts.atEnd())
{
ts.readLineInto(&line);
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 && parts.at(0) == "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;
ib.name = x;
ib.count = n;
inners.insert(outer, ib);
}
}
f.close();
QString myBag = "shiny gold";
holders(outers, holdsMyBag, myBag);
int totalcost = 0;
expense(inners, totalcost, myBag, 1);
qInfo() << holdsMyBag.count();
qInfo() << totalcost;
}
@randrew

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: https://gist.github.com/randrew/df1b4a31fb14692c0117edc6fdfb74ca

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