My Haskell solution. It uses the shunting-yard algorithm to convert it to a postfix string and then evals the postfix string. Today's part 2 was obvious the moment I read part 1 so I went for this approach. So to solve part 2 I only had to change a 2 to a 3. Took 24 seconds from submitting the answer to part 1 to submitting the answer to part 2.
importData.CharimportData.BifunctorasBfprecedence::Char->Int-- Change precedence level of + to 2 for part 1precedencec=casecof'+'->3;'*'->2;'('->1;')'->1;shouldPopStack::Char->Char->BoolshouldPopStackxtop=precedencex<=precedencetop&&top/='('popWhile::Char->(String,String)->(String,String)popWhilec(out,[])=(out,[])popWhilec(out,x:stack)=ifshouldPopStackcxthenpopWhilec(x:out,stack)else(out,x:stack)shunting::String->(String,String)->Stringshunting[](out,stack)=reversestack++outshunting('(':xs)(out,stack)=shuntingxs(out,'(':stack)shunting(')':xs)(out,stack)=let(ops,rest)=span(/='(')stackinshuntingxs(reverseops++out,tailrest)shunting('+':xs)yard=shuntingxs(Bf.second('+':)$popWhile'+'yard)shunting('*':xs)yard=shuntingxs(Bf.second('*':)$popWhile'*'yard)shunting(x:xs)(out,stack)=shuntingxs(x:out,stack)evalPostfix::String->(Int,String)evalPostfix('+':xs)=let(left,rest)=evalPostfixxsinBf.first(left+)$evalPostfixrestevalPostfix('*':xs)=let(left,rest)=evalPostfixxsinBf.first(left*)$evalPostfixrestevalPostfix(x:xs)=(digitToIntx,xs)main::IO()main=doinput<-lines<$>readFile"input.txt"print$sum$map(\s->fst$evalPostfix$shunting(filter(/=' ')s)([],[]))input
For further actions, you may consider blocking this person and/or reporting abuse
We're a place where coders share, stay up-to-date and grow their careers.
My Haskell solution. It uses the shunting-yard algorithm to convert it to a postfix string and then evals the postfix string. Today's part 2 was obvious the moment I read part 1 so I went for this approach. So to solve part 2 I only had to change a
2
to a3
. Took 24 seconds from submitting the answer to part 1 to submitting the answer to part 2.