constcalculator=operation=>{// verify that the string with the operation has the right format:// - a number// - optionally followed by 0 or more:// - a space// - an operator (+-*/)// - a space// - another numberif(!operation.match(/^\d+([\+\-\/\*]\d+)*$/))returnnull;// easy solution: now that we know the string has the format that we expect, // return (eval(operation));// ...but someone did it already, so let's go the long way :P// break the string by spacesletops=operation.split("");letopsSimple=[];// multiplication and division take priority// we create a new array that will only have numbers and + or -for(x=0;x<ops.length;x++){if(ops[x]==='*'){constval=opsSimple.pop();opsSimple.push(val*ops[x+1]);x++;}elseif(ops[x]==='/'){// do not allow division by zero!if(ops[x+1]==="0")return"Error! Division by zero!";constval=opsSimple.pop();opsSimple.push(val/ops[x+1]);x++;}else{opsSimple.push(ops[x]);}}// calculate the addtiions and substractions sequentiallyletresult=parseInt(opsSimple[0]);for(x=1;x<opsSimple.length;x=x+2){if(opsSimple[x]==='+'){result+=opsSimple[x+1];}else{result-=opsSimple[x+1];}}returnresult;}
usestd::{ops::{Add,Div,Mul,Sub},str::FromStr,};macro_rules!apply_op{($op:ident,$tokens:ident,$idx:ident)=>{{$tokens[$idx-1]=Token::Num($tokens[$idx-1].as_num()?.$op($tokens[$idx+1].as_num()?));$tokens.remove($idx+1);$tokens.remove($idx);}};}#[derive(Debug)]enumCalcError{Op,Input,}#[derive(Debug,Clone,Copy,PartialEq)]enumOp{Add,Sub,Mul,Div,}implFromStrforOp{typeErr=CalcError;fnfrom_str(s:&str)->Result<Self,Self::Err>{matchs{"+"=>Ok(Op::Add),"-"=>Ok(Op::Sub),"*"=>Ok(Op::Mul),"/"=>Ok(Op::Div),_=>Err(CalcError::Input),}}}#[derive(Debug,Clone,Copy,PartialEq)]enumToken{Num(i64),Op(Op),}implToken{fnas_num(&mutself)->Result<i64,CalcError>{matchself{Token::Num(x)=>Ok(*x),_=>Err(CalcError::Op),}}}implFromStrforToken{typeErr=CalcError;fnfrom_str(s:&str)->Result<Self,Self::Err>{ifletOk(x)=s.parse::<i64>(){returnOk(Token::Num(x));}else{letop=Op::from_str(s)?;returnOk(Token::Op(op));}}}fneval_str(s:&str)->Result<i64,CalcError>{letmuttokens=tokenize(s)?;letmuti=0;// do mul/divloop{// check if there are anyletops:Vec<&Token>=tokens.iter().filter(|e|**e==Token::Op(Op::Div)||**e==Token::Op(Op::Mul)).collect();ifops.is_empty(){break;}ifletSome(token)=tokens.get(i){ifletToken::Op(op)=*token{matchop{Op::Div=>apply_op!(div,tokens,i),Op::Mul=>apply_op!(mul,tokens,i),_=>{}}}i+=1;}else{// start again from the topi=0;}}i=0;// do add/subloop{// check if there are anyletops:Vec<&Token>=tokens.iter().filter(|e|**e==Token::Op(Op::Add)||**e==Token::Op(Op::Sub)).collect();ifops.is_empty(){break;}ifletSome(token)=tokens.get(i){ifletToken::Op(op)=*token{matchop{Op::Add=>apply_op!(add,tokens,i),Op::Sub=>apply_op!(sub,tokens,i),_=>{}}}i+=1;}else{// start again from the topi=0;}}// should only be one token left, return itOk(tokens[0].as_num()?)}// string to token Vecfntokenize(s:&str)->Result<Vec<Token>,CalcError>{letmutret=Vec::new();forcins.split(' '){ret.push(Token::from_str(c)?);}Ok(ret)}fnmain(){letinput="2 / 2 + 3 * 4 - 6";assert_eq!(eval_str(input).unwrap(),7);}
Oh macro_rules are something I haven't dug into and explored much yet! Definitely used the built in ones, but haven't written any yet.
Thanks for the example!
I was intimidated by them for a while and avoided the topic - tried one once and now they even end up in my daily puzzle solutions :P Truly not complicated to use, and super handy!
Regex was-?\d+, which would handle whole numbers, but with division in the mix, you have to handle the possibility of decimals.
The regex became -?\d+(?:\.\d+)?. (?: indicates it's not matching, so we're not grabbing the fractional aspect independently, \.\d_ matches one dot and however many digits, and )? closes the thing and matches only if found, so that it doesn't have to be a floating point number.
I recall this from Data Structures, and that there's ambiguity between handle from left and PEMDAS, which is a huge argument for Reverse Polish Notation.
For context (and an example I'm hitting in my testing), 4 - 6 - 2. By PEMDAS, they're of equal order, but it really depends on if you want (4 - 6) - 2 == -4 or 4 - (6 - 2) == 0.
With RPN, it's always number number operator, and variations on that are how we get precedence.
4 6 2 - - has 6 2 - in number number operator form and thus becomes 4, simplifying to 4 4 - and then 0.
4 6 - 2 - would get you the 4 6 - first, giving -2, then -2 2 -, which is -4`
Would anyone be able to help me abstract out that operation pattern? I'm a little stumped on how to de-duplicate this code, even though Haskell is great at that.
I remember doing this in C in college. It handled Real numbers (even Complex at one point, I believe), supported variables, could graph a function of x and even calculate the derivative. Much fun.
JavaScript
Live demo on CodePen
10 out of 10 challenges! :)
Although I was just able to make 2 using CSS only :-/
I'm gonna try to keep doing em each day in July if I can, you game lol?
I'm currently a day behind you since I didn't get this one done yesterday
Let's do it!
Alright, I'm gonna be the one who posts this.
If you add a check to verify the string is well formed, this will probably be the best and simplest answer.
Similarly unfair, the solution in R:
Warning: don't do this.
Rust, verbosely:
Oh macro_rules are something I haven't dug into and explored much yet! Definitely used the built in ones, but haven't written any yet.
Thanks for the example!
I was intimidated by them for a while and avoided the topic - tried one once and now they even end up in my daily puzzle solutions :P Truly not complicated to use, and super handy!
And, I see now that I don't handle non-whole-numbers, which the problem doesn't give me, but could come along anyway.
"5 / 4", for example.And that's entirely a regex problem.
Hrm.
Regex was
-?\d+, which would handle whole numbers, but with division in the mix, you have to handle the possibility of decimals.The regex became
-?\d+(?:\.\d+)?.(?:indicates it's not matching, so we're not grabbing the fractional aspect independently,\.\d_matches one dot and however many digits, and)?closes the thing and matches only if found, so that it doesn't have to be a floating point number.I recall this from Data Structures, and that there's ambiguity between handle from left and PEMDAS, which is a huge argument for Reverse Polish Notation.
For context (and an example I'm hitting in my testing),
4 - 6 - 2. By PEMDAS, they're of equal order, but it really depends on if you want(4 - 6) - 2 == -4or4 - (6 - 2) == 0.With RPN, it's always
number number operator, and variations on that are how we get precedence.4 6 2 - -has6 2 -innumber number operatorform and thus becomes4, simplifying to4 4 -and then0.4 6 - 2 -would get you the4 6 -first, giving-2, then-2 2 -, which is -4`Not that I do my regular math like this...
Haskell:
Would anyone be able to help me abstract out that operation pattern? I'm a little stumped on how to de-duplicate this code, even though Haskell is great at that.
Nim.
Did some cleanup using types. No more string->float->string conversions. Adding old solution below!
I’m (still) learning Erlang. This is my solution with the given operators and integer numbers. I’m quite satisfied:
To run it:
Then I extended it with:
125e-2 = 1.25);^;You can find it in this Gist, and try it:
parse_numbergot a bit out of hand, but I find the rest quite elegant. I like Erlang.My solution in js
I remember doing this in C in college. It handled Real numbers (even Complex at one point, I believe), supported variables, could graph a function of
xand even calculate the derivative. Much fun.a bit late... this is the solution in PHP
I missed this one yesterday! I'll get it done sometime this week though!