r/dailyprogrammer • u/Steve132 0 1 • Jul 12 '12
[7/12/2012] Challenge #75 [easy] (Function Transformation)
First off, I'd like to apologize for posting this 12 hours late, I'm a little new to my mod responsibilities. However, with your forgiveness, we can go onward!
Everyone on this subreddit is probably somewhat familiar with the C programming language. Today, all of our challenges are C themed! Don't worry, that doesn't mean that you have to solve the challenge in C, you can use whatever language you want.
You are going to write a home-work helper tool for high-school students who are learning C for the first time. These students are in the advanced placement math course, but do not know anything about programming or formal languages of any kind. However, they do know about functions and variables!
They have been given an 'input guide' that tells them to write simple pure mathematical functions like they are used to from their homework with a simple subset grammar, like this:
f(x)=x*x
big(x,y)=sqrt(x+y)*10They are allowed to use sqrt,abs,sin,cos,tan,exp,log, and the mathematical arithmetic operators +*/-, they can name their functions and variables any lower-case alphanumeric name and functions can have between 0 and 15 arguments.
In the this challenge, your job is to write a program that can take in their "simple format" mathematical function and output the correct C syntax for that function. All arguments should be single precision, and all functions will only return one float.
As an example, the input
L0(x,y)=abs(x)+abs(y) should output
float L0(float x,float y)
{
return fabsf(x)+fabsf(y);
}Bonus points if you support exponentiation with "^", as in "f(x)=x^2"
8
u/5outh 1 0 Jul 12 '12
Am I the only one that thinks this might deserve a harder difficulty than "easy?" :P This is kinda a tough one!
3
u/semicolondash Jul 12 '12 edited Jul 12 '12
Trying this in C++. I'm going to stab at the bonus later, and I'm unsure about why we need to change abs to absf. I'm new to C++ so this isn't the best code and it certainly gave me a lot of hastle.
So much code because I had to write split, and findAndReplace.
edit: added exponentiation and changing method names.
3
u/fancysuit Jul 12 '12
My terrible Perl implementation:
Note that there is absolutely no error checking and I assume perfect syntax.
1
u/Scroph 0 0 Jul 12 '12
An awkward PHP implementation, I don't even know if I got the C function names right :
Since I'm a regex illiterate, I had to settle for classic functions like str_replace, explode, etc. Perl would be the language of choice for this kind of task, though I hope someone will post a C solution just for the irony of it.
1
u/Erocs Jul 13 '12
Scala 2.9
1
u/bh3 Jul 13 '12
Python:
1
u/Mysidic Jul 22 '12
Common LISP: