How many elves does Santa need to deliver gifts?
JavaScript (ES6), 52 bytes
s=>eval(s.replace(/\D|$/g,m=>`.0*${m=="*"?3:2}+`)+0)
Explanation
Converts the input into a valid JavaScript statement. Replaces all *
with .0*3+
and all other (non-digit) symbols with .0*2+
. For example 8*9+*10
becomes 8.0*3+9.0*2+.0*3+10
. Finally it appends .0*2
to the end for the last nice count. This works because n.0
= n
and .0
= 0
.
s=>
eval( // execute the formed equation
s.replace(/\D|$/g, // replace each symbol (and also add to the end) with:
m=>`.0*${m=="*"?3:2}+` // case * = ".0*3+", else replace with ".0*2+"
)
+0 // add "0" to the end for the trailing "+"
)
Test
var solution = s=>eval(s.replace(/\D|$/g,m=>`.0*${m=="*"?3:2}+`)+0)
<textarea id="input" rows="6" cols="30">1*2+*+*4+1*
2*4+3*+1*6+*
*+*+4*2+1*1
*4+*3+1*+2*3
3*10+2*+*5+*</textarea><br />
<button onclick="result.textContent=solution(input.value)">Go</button>
<pre id="result"></pre>
Flex+C, 112 90 bytes
m=3,t;
%%
[0-9]+ t+=m*atoi(yytext);
\* m=2;
[+\n] m=3;
%%
main(){yylex();printf("%d",t);}
The first character is a space. Compile with:
flex -o santa.c santa.l
cc santa.c -o santa -ll
Reads from STDIN, writes to STDOUT. Input is terminated by EOF (Ctrl+D in console).
Pyth, 21 bytes
ssMs*VCcR\*scR\+.z_S3
Multi-line example
Single-line test suite
ssMs*VCcR\*scR\+.z_S3
.z Take a input, as a list of lines.
cR\+ Chop each line on '+'.
s Flatten into list of strings.
cR\* Chop each line on '*'.
C Transpose, into a list of naughty and nice.
*V _S3 Vectorized multiplication with [3, 2, 1]. This replicates
the naughty list 3 times and the nice list 2 times.
s Flatten.
sM Convert each string to an int.
s Sum.