Input
A string.
Output
The sum of all integers in the line.
Constraints
1≤Length of line≤500
Sample test Case
Input
the 5is 108 seCONd4 a
Output
117
Explanation
Sum is: 5+108+4=117
.œþOà
Try it online or verify a few more test cases. (Times out for the larger test cases due to the .œ
builtin.)
þмS¡þO
Try it online or verify a few more test cases.
Explanation:
.œ # Get all partitions of the (implicit) input-string,
# which are all possible ways of dividing the input-strings into substrings
þ # Only leave the items consisting of digits for each partition
# (in the new version of 05AB1E, an explicit `€` is required)
O # Sum each inner list
à # Pop and push its maximum
# (after which the result is output implicitly)
þм # Only leave the non-digits of the (implicit) input-string
# i.e. "the 5is 108 seCONd4 a" → "the is seCONd a"
S # Split it into a list of characters
# → ["t","h","e"," ","i","s"," "," ","s","e","C","O","N","d"," ","a"]
¡ # Split the (implicit) input-string by each of these characters
# → ["","","","","5","","","108","","","","","","","4","",""]
þ # Remove the empty strings by only leaving the digits
# → ["5","108","4"]
O # And sum these numbers (which is output implicitly)
# → 117
s=>eval(s.match(/\d+/g).join`+`)
Match all digits and join them by a +
turning it into 5+108+4, eval the result.
Only works on positive integers.
Saved 2 bytes thanks to Arnauld
f=
s=>eval(s.match(/\d+/g).join`+`)
g=()=>b.innerHTML = f(a.value)
g()
<input id=a value="the 5is 108 seCONd4 a" onkeyup="g()">
<pre id=b>
console.log(f.toString().length)
, but it's not 100% reliable either.
\$\endgroup\$
After seeing the PowerShell entry I was able to golf this further.
function(s)eval(parse(,,gsub('\\D+','+0',s)))
Anonymous tacit prefic function
+/#⍎¨∊∘⎕D⊆⊢
⊢
the argument
⊆
partitioned (runs of True become pieces, run of False are separators) by
∊
membership
∘
of
⎕D
the set of digits
#⍎¨
evaluate each in the root namespace
+/
sum
<<<$[${1//[^0-9]/+0}]
${1 } # the 5is 108 seCONd4 a
${1//[^0-9]/+0} # +0+0+0+05+0+0+0108+0+0+0+0+0+0+04+0+0
$[${1//[^0-9]/+0}] # 117
Unfortunately, bash complains because it interprets 0108
as octal. Zsh does not (unless setopt octalzeroes
)
for n in ${1//[!0-9]/ };{((s+=n));};echo $s
Replaces every non-number with a space, and then sums them together.
-5 bytes thanks to GammaFunction
\d+
$*
1
IΣ⁺ψS
Try it online! Link is to verbose version of code. Explanation: Charcoal's Sum
operator automatically extracts numbers from a string, however if the string contains no non-digit characters then instead it takes the digital sum, so I concatenate a null byte to avoid this. The result is then cast back to string for implicit output.
sum.map read.words.map f
f x|'/'<x,x<':'=x
f _=' '
There's probably a better way, but this is the most obvious one.
Why not. Obligatory regex answer. Could probably dock off 6 by using Python 2, but whatever. Doesn't apply anymore since I'm using an eval approach instead of using map.
import re;x=lambda y:eval('+'.join(re.findall('\d+',y)))
Explanation:
import re; # Import regex module
x=lambda y: eval( ) # Run as Python code
'+'.join( ) # Joined by '+'
re.findall('\d+',y) # A list of all matches of regex \d+ in string y
z == l[1]
instead of z is l[1]
though. The current code can give false negatives if the numbers get high enough.
\$\endgroup\$
This is a lambda from String
to int
.
s->{var r=0;for(var n:s.split("\\D"))r+=new Long("0"+n);return r;}
Negative integers aren't supported. Presumably that's okay.
[^0-9]
for \D
for a few bytes, also you can switch long
and String
for var
(though you will have to change the return type to int
\$\endgroup\$
*?+
instead of .join ?+
for -7 bytes. See ary * str
\$\endgroup\$
Mar 9, 2019 at 6:41
?|i.I!/s+q;;>p.O@
? |
i .
I ! / s + q ; ;
> p . O @ . . .
. .
. .
A fairly simple one. I
in cubix will take the first integer in the input and push it to the stack. This has the effect of skipping all the characters. The rest of it is dealing with the additional and detecting the end of the input.
I!
Input an integer and test it for 0s+q;;
If not zero, swap TOS (forces and initial 0) and add. Push result to the bottom of stack and clean out the top. Return to beginning./i?
If zero, redirect and do a character input to check|?;/
If positive (character) turn right into a reflect, this then pushes it back through the checker ?
and turns right onto the pop from stack, leaving 0 on TOS. The IP then gets redirected back into the main loop.I>p.O@
if negative (end of input) turn left, do integer input, bring the bottom of stack to top, output and halt.<?=array_sum(preg_split('(\D)',$argn));
Run with php -nF
input is from STDIN. Example:
$ echo the 5is 108 seCONd4 a | php -nF sumint.php
117
This works because I
simply scans the input stream for the next token that looks like a number, ignoring anything else.
~Ilj~#
>K+O@
+/⍎⍵
\D
+/
sum of
⍎
evaluation as APL of
⍵
the result of
\D
replacing each non-digit with
a space
Sum##N=>MatchAll&"\\d+"
A more interesting, but indirect, answer (37 bytes): {Sum!Reap[ReplaceF[_,/"\\d+",Sow@N]]}
Sum##N=>MatchAll&"\\d+"
This has the form:
f##g=>h&x
which, when expanded and parenthesized, becomes:
f ## (g => (h&x))
##
composes two functions together, =>
creates a function mapping the left function over the result of the right function, and &
binds an argument to a side of a function. For input _
, this is equivalent to:
{ f[Map[g, h[_, x]]] }
First, then, we MatchAll
runs of digit characters (\\d+
). After, we convert each run to an actual integer using the N
function. Finally, we take the sum of these numbers using Sum
.
{+/⍎¨⍵⊂⍨⍵∊⎕D}
test:
f←{+/⍎¨⍵⊂⍨⍵∊⎕D}
f 'the 5is 108 seCONd4 a'
117
a=>System.Text.RegularExpressions.Regex.Replace(a,@"\D+"," ").Split(' ').Select(x=>x==""?0:int.Parse(x)).Sum();
105 bytes + 25 bytes for regex import
s->{long c=0;for(Matcher m=Pattern.compile("\\d+").matcher(s);m.find();c+=new Long(m.group()));return c;}
Try it online!
Explanation
s->{ // Lambda function
long c=0; // Sum is zero
for(Matcher m=Pattern.compile("\\d+").matcher(s); // Prepare regex matcher
m.find(); // While the string contains unused matches...
c+=new Long(m.group())); // Add those matches to the output
return c; // Return the output
}
S =INPUT
D S SPAN('0123456789') . N REM . S :F(O)
O =O + N :(D)
O OUTPUT =O
END
Swift, 109 bytes
func s(a:String){var d=0,t=0;a.forEach{(c) in if let e=Int(String(c)){d=d*10+e}else{t+=d;d=0}};t+=d;print(t)}
$+a@XI
Treats -123
as a negative integer. Try it online!
a Command-line input
@XI Regex find all integers (XI is a variable predefined as the regex `-?\d+`)
$+ Fold on +
If hyphens should be ignored rather than treated as minus signs, then the following works for 7 bytes:
$+a@+XD
XD
is a preset variable for `\d`
; +XD
adds the regex +
modifier to it, making it match 1 or more digits.
s->java.util.Arrays.stream(s.split("\\D")).filter(t->!t.isEmpty()).mapToLong(Long::new).sum()
-4 bytes
by using Long::new
instead of Long::valueOf
.
-1 byte
by shortening the regex - if we're already removing empty strings later, making some extras when splitting is fine.
s-> // Lambda (target type is ToLongFunction<String>)
java.util.Arrays.stream( // Stream the result of
s.split("\\D") // splitting on non-digits
)
.filter(t->!t.isEmpty()) // Discard any empty strings
.mapToLong(Long::new) // Convert to long
.sum() // Add up the stream's values.
"the 5is 108 seCONd4 a"
will result in117
because5+108+4=117
). Also, every 'question' here should have a winning condition tag. In this case I assume it's [code-golf] (being the shortest possible solution)? \$\endgroup\$string x='-12hello3';
are you counting negative integers (i.e., -12+3 === -9)? \$\endgroup\$