It's a hashing algorithm, helpfully called the HASH
algorithm. Cute.
int HASH(string s)
{
int value = 0;
for (char c : s)
{
value += c;
value *= 17;
value %= 256;
}
return value;
}
It took longer to read the writeup than to implement that, and sum the input.
Ah, okay. Now it's a HASHMAP
. Cute?
Part 2 is significantly more complex... not impossible to deal with, but still complex. I might be able to get away with a map of string arrays, and just swap stuff around as need be?
Either way, just implement as described in part 2:
for (string step : sequence)
{
if (step.back() == '-')
{
string prefix = step.substr(0, step.length() - 1);
int hash = HASH(prefix);
int removeIndex = -1;
for (int i = 0; i < boxes[hash].size(); i++)
{
if (boxes[hash][i].substr(0, prefix.length()) == prefix)
{
removeIndex = i;
break;
}
}
if (removeIndex >= 0)
{
boxes[hash].erase(boxes[hash].begin() + removeIndex);
}
}
else
{
auto parts = split(step, "=");
int hash = HASH(parts[0]);
int removeIndex = -1;
for (int i = 0; i < boxes[hash].size(); i++)
{
if (boxes[hash][i].substr(0, parts[0].length()) == parts[0])
{
removeIndex = i;
break;
}
}
boxes[hash].push_back(step);
}
}