[Home] [Puzzles & Projects] [Delphi Techniques] [Math topics] [Library] [Utilities]


Problem DescriptionHere's a nice little puzzle: Consider the equation below, where "op" represents one of the four basic operators +
(addition),  (subtraction), * (multiplication) or / (division). Source:: Adapted from an educational newsgroup posting by Kaidy Educational Resources Background & TechniquesSince we are working with three operator locations, each with four possible values, there are only 4X4X4=64 possible arrangements. Hardly worth implementing a full scale expression parser and evaluator. (although the Scientific Graphic Calculator project has one that would do nicely). Instead, let's start by looking at the order of operations required to evaluate the expression, '*' and ' /' must be performed before '+' and ''. We'll call '*' and '/' high priority and '+' and '' low priority operations. There are only possible 8 sequences of high and low priority operations (low, low, low), (low, low, high), (low high, low), (low, high, high), (high, low, low), (high, low, high), (high, high, low), and (high, high, high). So 9+2*31, for example belongs to the (low, high, low) category. If we can determine which of these 8 patterns applies to a particular expression, then three "If" tests for each pattern, one for each operator, performed with high priority first, should be enough to distinguish '*' and '/' from '+' and ''. Function Eval does this. Now we have to figure out how to pass all 64 of the possible expressions to Eval. We'll just arbitrarily assign values 1,2,3 and 4 to operations +, , *, and / respectively. Procedure ShowValues uses a triply nested loop to do this. Since we're generating all 64 solutions but only want those that evaluate to 0 through 9, ShowValues takes high and low limits as parameters. Given that, we might as well add a button to show all values  just in case someone wonders about the highest possible value. for example. ShowValues adds formatted versions of the equations to a stringlist  we'll put the result values first so that we can easily sort equations before displaying them. Notice too that 16 of the 64 values do not produce integer expression at all  namely those with 3 / 2 as the middle operation. I return 9999 from Eval as a special flag value to indicate this case. Running/Exploring the Program
Suggestions for Further Explorations

[Feedback] [Newsletters (subscribe/view)] [About me]Copyright © 20002018, Gary Darby All rights reserved. 