How to golf evaluation of math expression in MySQL?

Score 69

select * from expressions
where elt(ord(operation)/2-20,a*b,a+b,a-b,a/b)=c

Takes inspiration from Marmite Bomber's use of elt, but uses a magic formula. Indexes into the list via ord(operation)2/-20, which buckets the four character codes across 1 to 4 by abusing elt's rounding behavior.

-1 thanks to Arnauld, who improved on the modulo reduction.

-1 thanks to Bubbler, who found a better non-modulo formula.

Score 73

select * from expressions
where elt(instr('*/-+',operation),a*b,a/b,a-b,a+b)=c

This is my best guess as to the 73 you mention other people have gotten in the question.


MySQL, 82 74 bytes

select * from expressions
where 
elt(locate(operation,'+-/*'),a+b,a-b,a/b,a*b)=c

output

a           b           operation c           
----------- ----------- --------- ----------- 
2           3           +         5           
8           5           -         3 

Explanation

ELT() returns the Nth element of the list of strings (the expressions are evaluated and converted to strings)

LOCATE Return the position of the first occurrence of substring

Tags:

Code Golf

Tips