12
\$\begingroup\$

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

\$\endgroup\$
8
  • 6
    \$\begingroup\$ Hi there, welcome to PPCG. Challenges for a single language are usually frowned upon here at PPCG. Maybe you could change it to a general challenge: given a string, output the sum of all numbers in the string, ignoring everything else (i.e. "the 5is 108 seCONd4 a" will result in 117 because 5+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\$ Mar 7, 2019 at 9:54
  • 4
    \$\begingroup\$ It appears that you've posted a similar question on SO, which tends to confirm that it was not designed to be a PPCG challenge and you are looking for 'usable' code rather than golfed code. I'd recommend to improve your original question on SO instead, so that it better fits the rules of the site. \$\endgroup\$
    – Arnauld
    Mar 7, 2019 at 10:15
  • 4
    \$\begingroup\$ I've overhauled your post to fit our standards. Feel free to edit if the result doesn't suit you. \$\endgroup\$
    – Adám
    Mar 7, 2019 at 11:43
  • 4
    \$\begingroup\$ @Adám codegolf.meta.stackexchange.com/a/14840/34718 \$\endgroup\$
    – mbomb007
    Mar 7, 2019 at 17:12
  • 2
    \$\begingroup\$ What about this case string x='-12hello3'; are you counting negative integers (i.e., -12+3 === -9)? \$\endgroup\$ Mar 15, 2019 at 10:17

31 Answers 31

5
\$\begingroup\$

05AB1E (legacy), 5 bytes

.œþOà

Try it online or verify a few more test cases. (Times out for the larger test cases due to the builtin.)

05AB1E, 11 6 bytes

þм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
\$\endgroup\$
1
  • 1
    \$\begingroup\$ Oh hey, clever usage of ¡! \$\endgroup\$ Mar 9, 2019 at 15:33
4
\$\begingroup\$

Javascript, 34 32 bytes

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>

\$\endgroup\$
3
  • \$\begingroup\$ I guess using string.length in the console to count characters isn't a good idea when it contains escape characters... Whoops, fixed it. Thx again \$\endgroup\$ Mar 7, 2019 at 10:19
  • \$\begingroup\$ A slightly better option would be console.log(f.toString().length), but it's not 100% reliable either. \$\endgroup\$
    – Arnauld
    Mar 7, 2019 at 10:39
  • \$\begingroup\$ Or just using TIO... \$\endgroup\$
    – Jo King
    Mar 7, 2019 at 11:35
4
\$\begingroup\$

Perl 6, 14 bytes

{sum m:g/\d+/}

Try it online!

Anonymous code block that returns the sum of all series of digits

\$\endgroup\$
4
\$\begingroup\$

R, 64 48 45 bytes

After seeing the PowerShell entry I was able to golf this further.

function(s)eval(parse(,,gsub('\\D+','+0',s)))

Try it online!

\$\endgroup\$
2
  • \$\begingroup\$ t= is sufficient here rather than text \$\endgroup\$
    – Giuseppe
    Mar 8, 2019 at 3:35
  • \$\begingroup\$ Thanks, I always forget about partial matching, (and the string of ,,, til you get to the option you want). \$\endgroup\$
    – CT Hall
    Mar 8, 2019 at 3:36
3
\$\begingroup\$

APL (Dyalog Unicode), 11 bytes

Anonymous tacit prefic function

+/#⍎¨∊∘⎕D⊆⊢

Try it online!

 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

\$\endgroup\$
3
\$\begingroup\$

Zsh, 21 bytes

<<<$[${1//[^0-9]/+0}]

Try it online!

  ${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)

\$\endgroup\$
3
\$\begingroup\$

Bash, 43 bytes

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

\$\endgroup\$
2
3
\$\begingroup\$

Retina 0.8.2, 8 bytes

\d+
$*
1

Try it online!

  • The first line matches all numbers
  • The second line replaces these by 1s, repeated said number of times
  • The last line is a match, and counts the total number of 1s in the string
\$\endgroup\$
2
\$\begingroup\$

PowerShell, 29 bytes

($args-replace'\D+','+0')|iex

Try it online!

\$\endgroup\$
1
  • 1
    \$\begingroup\$ I was able to improve my R answer due to the +0 part. \$\endgroup\$
    – CT Hall
    Mar 8, 2019 at 3:28
2
\$\begingroup\$

Charcoal, 5 bytes

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.

\$\endgroup\$
2
\$\begingroup\$

Haskell, 50 bytes

sum.map read.words.map f
f x|'/'<x,x<':'=x
f _=' '

Try it online!

There's probably a better way, but this is the most obvious one.

\$\endgroup\$
1
\$\begingroup\$

Python 3, 63 59 56 bytes

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

Try it online!

\$\endgroup\$
1
  • \$\begingroup\$ Nice! In your TIO you should use z == l[1] instead of z is l[1] though. The current code can give false negatives if the numbers get high enough. \$\endgroup\$
    – Jakob
    Mar 9, 2019 at 17:48
1
\$\begingroup\$

Java 10, 66 bytes

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.

Try It Online

Acknowledgments

\$\endgroup\$
1
  • 1
    \$\begingroup\$ You can switch [^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\$
    – Gymhgy
    Mar 8, 2019 at 6:13
1
\$\begingroup\$

Ruby, 32 27 characters

->s{eval s.scan(/\d+/)*?+}

Acknowledgments

\$\endgroup\$
1
  • 1
    \$\begingroup\$ Welcome to PPCG! You could use *?+ instead of .join ?+ for -7 bytes. See ary * str \$\endgroup\$ Mar 9, 2019 at 6:41
1
\$\begingroup\$

Cubix, 17 bytes

?|i.I!/s+q;;>p.O@

Try it online!

    ? |
    i .
I ! / s + q ; ;
> p . O @ . . .
    . .
    . .

Watch it run

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 0
  • s+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.
\$\endgroup\$
1
\$\begingroup\$

PHP, 40 39 bytes

<?=array_sum(preg_split('(\D)',$argn));

Try it online!

Run with php -nF input is from STDIN. Example:

$ echo the 5is 108 seCONd4 a | php -nF sumint.php    
117
\$\endgroup\$
1
\$\begingroup\$

Haskell, 43 bytes

f s|[(n,r)]<-reads s=n+f r|h:t<-s=f t|1>0=0

Try it online!

Makes use of reads.

\$\endgroup\$
1
\$\begingroup\$

Ahead, 13 bytes

This works because I simply scans the input stream for the next token that looks like a number, ignoring anything else.

~Ilj~#
 >K+O@

Try it online!

\$\endgroup\$
0
\$\begingroup\$

QuadR, 9 bytes

+/⍎⍵
\D
 

Try it online!

+/ sum of

 evaluation as APL of

 the result of

\D replacing each non-digit with

 a space

\$\endgroup\$
0
\$\begingroup\$

Japt -x, 5 bytes

f/\d+

Try it online!

\$\endgroup\$
1
  • 2
    \$\begingroup\$ 3 bytes \$\endgroup\$
    – Shaggy
    Mar 7, 2019 at 20:33
0
\$\begingroup\$

Attache, 23 bytes

Sum##N=>MatchAll&"\\d+"

Try it online!

A more interesting, but indirect, answer (37 bytes): {Sum!Reap[ReplaceF[_,/"\\d+",Sow@N]]}

Explanation

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.

\$\endgroup\$
0
\$\begingroup\$

APL(NARS), chars 13, bytes 26

{+/⍎¨⍵⊂⍨⍵∊⎕D}

test:

  f←{+/⍎¨⍵⊂⍨⍵∊⎕D}
  f 'the 5is 108 seCONd4 a'
117
\$\endgroup\$
0
\$\begingroup\$

C# (Visual C# Interactive Compiler), 117 111 bytes

a=>System.Text.RegularExpressions.Regex.Replace(a,@"\D+"," ").Split(' ').Select(x=>x==""?0:int.Parse(x)).Sum();

Try it online.

\$\endgroup\$
0
\$\begingroup\$

Perl 5 -p, 17 bytes

s/\d+/$\+=$&/eg}{

Try it online!

\$\endgroup\$
0
\$\begingroup\$

Japt v2.0a0 -x, 3 bytes

Another test drive for my (very-WIP) interpreter.

q\D

Try it

q\D     :Implicit input of string
q       :Split on
 \D     :  Non-digit characters (/[^0-9]/)
        :Implicitly reduce by addition and output
\$\endgroup\$
0
\$\begingroup\$

Java 8, 53 130 bytes

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
   }
\$\endgroup\$
3
  • 2
    \$\begingroup\$ I don't think this is correct: the (only) example by the OP suggests that consecutive digits should form a single integer, so "123" should produce 123, not 6 like your code does. \$\endgroup\$
    – Michail
    Mar 9, 2019 at 20:19
  • \$\begingroup\$ That's unfortunate, I'll revise when I can \$\endgroup\$ Mar 9, 2019 at 21:48
  • \$\begingroup\$ @Michail revised \$\endgroup\$ Mar 24, 2019 at 22:06
0
\$\begingroup\$

SNOBOL4 (CSNOBOL4), 81 bytes

	S =INPUT
D	S SPAN('0123456789') . N REM . S	:F(O)
	O =O + N	:(D)
O	OUTPUT =O
END

Try it online!

\$\endgroup\$
0
\$\begingroup\$

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)}

Try it online!

\$\endgroup\$
0
\$\begingroup\$

Pip, 6 bytes

$+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.

\$\endgroup\$
0
\$\begingroup\$

Java (JDK), 98 94 93 bytes

s->java.util.Arrays.stream(s.split("\\D")).filter(t->!t.isEmpty()).mapToLong(Long::new).sum()

Try it online!

-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.

Explained

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.
\$\endgroup\$

Not the answer you're looking for? Browse other questions tagged or ask your own question.