Since yesterday's problem was the first one where it took more than a second to run, I figured it was time to start adding a little flair to the output. After some annoying fussing with how the output looks, there's a nice little grid that outputs the answers for me and how long it took to run!
Use Real Input? (y/N): y
+--------------------+
| Results |
+---+------+---------+
| 1 | 12 | 2ms |
| 2 | 3456 | 11467ms |
+--------------------+
This seems interesting....
At least for part 1, I'll just do a depth-first search; just try every possibility until a valid solution is found. I'll even make sure to pass in the valid operators (+*
) as a parameter, because I can see Part 2 likely adding more operators, and I would like to just solve this once.
private bool IsValidEquation(long target, List<long> terms, char[] operators, long result)
{
if (terms.Count == 0)
{
return result == target;
}
long curTerm = terms.First();
var nextTerms = new List<long>(terms);
nextTerms.RemoveAt(0);
foreach (char op in operators)
{
var nextResult = op switch
{
'+' => result + curTerm,
'*' => result * curTerm,
_ => throw new NotImplementedException()
};
if (IsValidEquation(target, nextTerms, operators, nextResult)) return true;
}
return false;
}
Interestingly, this was the first day I had to modify some of the more fundamental code. int
wasn't large enough to handle some of the inputs, so I had to switch to a long
, something I had forgotten about. I updated the interfaces and all of the previous day's problems. Luckily int
readily casts to long
without issue.
Oooooh, this Part 2 is worse than I thought; a ||
concatenation operator that is just... fun. I'm going to just use a one-character |
instead in my code as it doesn't quite matter, but it doesn't seem too difficult, just adding a different condition to the switch statement.
var nextResult = op switch
{
'+' => result + curTerm,
'*' => result * curTerm,
'|' => long.Parse(result.ToString() + curTerm.ToString()),
_ => throw new NotImplementedException()
};
That has to be the easiest Part 2 for me in a long time.