Define a mathematical expression in English
+2
−0
Background
Inspired by this challenge that is also a mathematical English translator.
Challenge
Write a program that translates a mathematical expression using English with the following specifications:
- The expression can only take in numbers, letters from the English alphabet, the equal sign, and the arithmetic operators. No, exponents aren't arithmetic.
- If the target character(s) is a/are number(s):
- The number range can only be from
-999
up to999
. - When in the tens place, use the dash (
-
) when there are spaced numberings. For example,21
istwenty-one
. - When in the hundreds place, add
and
to the string if the tens and/or the ones place aren't empty. For example,125
isone hundred and twenty-five
. - If the number is negative, use
negative
before the number. For example,-13
isnegative thirteen
.
- The number range can only be from
- If the target character is a letter:
- The input should only take 1 letter.
- When put on the result, the letter must be capitalized.
- If the target character is a symbol:
-
+
isplus
. -
-
isminus
. -
*
istimes
. -
/
isdivided by
. -
=
isequals
oris equal to
.
-
- Parentheses shouldn't be inputted.
- Whitespaces are ignored.
- Any character that's not part of the specification is ignored.
- Trailing whitespaces and newlines are allowed.
- This is code-golf, so the shortest program for each language wins!
Test Cases
// Input
# Output
14
fourteen
1+2
one plus two
53 /3
fifty-three divided by three
6 +2* 7 =20
six plus two times seven equals twenty
8*8*8 * 8 * 8 -1
eight times eight times eight times eight times eight minus one
= 4
is equal to four
x + y = z
X plus Y equals Z
-5 +- 6
negative five plus negative six
Testcases by [**@celtschk**](https://codegolf.codidact.com/comments/thread/4623#comment-13896):
500
five hundred
129
one hundred and twenty-nine
0+0=0
zero plus zero equals zero
0 -- 0 = 0
zero minus negative zero equals zero
1 answer
+2
−0
C (gcc), 774 bytes
#define S strcat(o,
#define I(s)if(n)S s);else{S" ");return;}
#define B);break;case
n,N,s;char*i,o[999],*d[]={"zero ","one ","two ","three ","four ","five ","six ","seven ","eight ","nine ","ten ","eleven ","twelve ","thir","four","fif","six","seven","eigh","nine"},*t[]={"twenty","thirty","forty","fifty","sixty","seventy","eighty","ninety"},l[]="A";p(){if(n>99){S d[n/100]),S"hundred"),n%=100;I(" and ")}if(n>19){S t[n/10-2]);n%=10;I("-")}S d[n]);if(n>12)S"teen ");}main(int c,char**v){i=*++v;for(;*i;i++){if(*i>47&*i<58)n=10*n+*i-48,N=1;else if(*i==32);else if(*i>64)*l=*i&95,N=2,S" "+!s++),S l);else{S" "+!s++);N&1&&p(o);switch(*i-42){case 1:S"plus"B 3:if(N)S"minus");else S"negative"B 0:S"times"B 5:S"divided by"B 19:S"equals"B 9:;}n=N=0;}}if(N&1)S" "+!s),p();puts(o);}
This code takes input from the command line, and outputs on stdout.
3 comment threads