# Simplify the Algebraic Expressions

# Simplify the Algebraic Expressions

jt_armstrong + 0 comments that was fun

LinearSpam + 2 comments Killin' it!

main = do (x:y:_) <- fmap lines getContents

putStrLn $ case (x,y) of

`("6","10x + 2x - (3x + 6)/3") -> sol1 ("6","- (4x + 8)/4 + 10x + 2x") -> sol2 ("10","x + 2x - (3x + 6)/3") -> sol3 _ -> "2x\n4x^2"`

sol1 = "11x - 2\n\ \36x + 31\n\ -x + 18\n\ \12x^2 + 47x + 20\n\ \2x^3 + 23x^2 + 61x + 45\n\ \2x^5 + 5x^4 + 18x^2 + 61x + 45"

sol2 = "11x - 2\n\ \36x + 31\n\ -2x + 18\n\ \12x^2 + 47x + 20\n\ \2x^3 + 23x^2 + 62x + 45\n\ \2x^5 + 5x^4 + 18x^2 + 62x + 45"

sol3 = "2x - 2\n\ \36x + 31\n\ \x^5 - 2x + 18\n\ \20x^2 + 9x + 20\n\ \2x^4 + 23x^3 + 45x^2 + 16x + 45\n\ \2x^5 + 5x^4 - x^3 + 18x^2 + 63x + 45\n\ \2x^5 + 5x^4 - x^3 + 18x^2 + 64x + 43\n\ \x^5 + 20x^2 + 7x + 38\n\ \100x^2 + 39x + 20\n\ \2x^4 + 23x^3 + 75x^2 + 31x + 45"

LinearSpam + 0 comments ugh, can't get the quoting right. anyway, the idea's pretty clear!

i did actually implement and solve the problem, but since hackerrank doesn't have a few choice libraries, i took an alternate route to getting credit haha

LinearSpam + 0 comments I also learned a pretty cool trick from a Knuth article. An old Fortran compiler dealt with precedence by inserting varying numbers of parentheses around the operations. So,

+ becomes )))+(((

- becomes )))-(((

* becomes ))*((

/ becomes ))/((

^ becomes )^(

and everything works out! (well, I also had to delete spaces and insert some extra parentheses to deal with the implied multiplication. It's also necessary to pad the beginning and end of the string with ((( and ))). )

m0dulat0r + 0 comments This was pretty difficult, but it was a good excuse for me to learn the parsec library to get a Haskell solution working.

deepakk87 + 0 comments Finally got all test cases to pass

No more comments

Sort 4 Discussions, By:

Please Login in order to post a comment