I’m developing a program that makes basic calculations using words instead of numbers. E.g. five + two would output seven.
The program becomes more complex, taking input such as two_hundred_one + five_thousand_six
(201 + 5006)
Through operator overloading methods, I split each number and assign it to it’s own array index.
two would be [0], hundred is [1], and one is [2]. Then the array recycles for 5006.
My problem is, to perform the actual calculation, I need to convert the words stored in the array to actual integers.
I have const string arrays such as this as a library of the words:
const string units[] = { "", "one", "two", "three", "four", "five", "six", "seven", "eight", "nine" };
const string teens[] = { "ten", "eleven", "twelve", "thirteen", "fourteen", "fifteen", "sixteen", "seventeen", "eighteen", "nineteen" };
const string tens[] = { "", "", "twenty", "thirty", "forty", "fifty", "sixty", "seventy", "eighty", "ninety" };
If my ‘token’ array has stored in it two hundred one in index 0, 1, and 2, I’m not sure what the best way to convert these to ints would involve.
Part of the trick for me was to parse the tokens backwards, rather than forwards. And to maintain a scale factor as you move back through the tokens. For each token you either add to the current value (scaled by the current value of the scalefactor) or adjust the scalefactor, depending on which token you encounter.
Here’s my implementation (some bits are not included, and you’d need to add a little logic to handle millions).