This post is part of a series on Mohammad Anwar’s excellent Weekly Challenge, where hackers submit solutions in Perl, Raku, or any other language, to two different challenges every week. (It’s a lot of fun, if you’re into that sort of thing.)
Challenge #1 this week is as follows:
You are given a string “123456789”. Write a script that would insert ”+” or ”-” in between digits so that when you evaluate, the result should be 100.
I am going to add the additional constraint that we want all possible solutions, because that is a much stronger statement, and not that difficult to do. There are a few ways we could go about it, but one way that will ensure we traverse the entire search tree is to try every permutation of +, -, and ” (i.e., nothing) in between each decimal digit. As a minimal example, given the string 12, we would have the following expressions:
+1 +1-2 -1+2 +12
+1+2 -1 -1-2 -12
Recursion gives us a search tree for free, so we’ll use that.
Continue reading “Only 100, please”