One very useful exercise--as well as one with practical application--is to create a program that reads in a formulae, and then solves it. This can be applied to creating a calculator all the way down to creating a preparser for a SQL statement. Because of time, I will break this over several days and over several possible approaches.
Problem:
You have an input of several characters, made up of symbols and numbers. Create a program to reduce the formulae down to a single solution.
Example:
5+3-(10 % 5)
(50-30)*3
Knowns:
The possible sets of input will be as follows: numbers between 0-9, at least one "period" for known floating point numbers, opening and closing parenthesis, and the operands.
Possible Operands:
+: Addition
-: Subtraction
*: Multiplication
/: Division
%: Modulous
^: Exponent
@: Square Root (yes, I know, I made that up)
The final known is, of course, the order of evaluation. Parenthesis first, then multiplication/division/exponential/modulous, addition/subtraction and finally our new "Square Root" function.
Application:
The way that I would approach this problem is the creation of a "First-In-First-Out" list of the characters in the file. This can be accomplished with any number of ways, including list objects or just an array of characters. But the first thing to do is to seperate the whole of the formulae into seperate "tokens" that can then be sorted into proper priority.
Monday, February 12, 2007
Subscribe to:
Posts (Atom)