-
-
Save randrew/f976e711e852ad3378fb63becc1dc61f to your computer and use it in GitHub Desktop.
aoc 2020 day 7
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#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; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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