16
\$\begingroup\$

Task

The task is very simple. Given a non-empty string containing numbers, uppercase and lowercase letters, output the sum of the remaining numbers. For example:

a1wAD5qw45REs5Fw4eRQR33wqe4WE

Filtering out all the letters would result into:

 1   5  45   5  4    33   4

The sum of these numbers is 1 + 5 + 45 + 5 + 4 + 33 + 4 = 97. So the output would be 97.

Test Cases

a > 0
0 > 0
5 > 5
10 > 10
a0A > 0
1a1 > 2
11a1 > 12
4dasQWE65asAs5dAa5dWD > 79
a1wAD5qw45REs5Fw4eRQR33wqe4WE > 97

This is , so the submission with the least amount of bytes wins!

\$\endgroup\$
  • \$\begingroup\$ I knew I had written that Labyrinth program before... here is the same challenge but with negative numbers as well (which makes a surprisingly big difference for some languages, so I don't think they're dupes). \$\endgroup\$ – Martin Ender Feb 12 '16 at 18:06
  • \$\begingroup\$ @MartinBüttner Looks like that one doesn't include negative numbers: "-n (where n is an integer) is not counted as a negative n, but as a hyphen followed by n." \$\endgroup\$ – Paul Feb 13 '16 at 3:18
  • \$\begingroup\$ Oh, I see what you mean. You're saying it has hyphens and this one doesn't. \$\endgroup\$ – Paul Feb 13 '16 at 3:20

31 Answers 31

22
\$\begingroup\$

GS2, 2 bytes

Wd

Try it online!

How it works

W     Read all numbers.
      For input x, this executes map(int, re.findall(r'-?\d+', x)) internally.
 d    Compute their sum.
\$\endgroup\$
  • 11
    \$\begingroup\$ Well, this was unexpected... \$\endgroup\$ – Adnan Feb 12 '16 at 16:25
  • \$\begingroup\$ @Adnan: It's Dennis. Given enough time he can find a solution to any code golf in less than 4 bytes. \$\endgroup\$ – Deusovi Feb 17 '16 at 12:10
13
\$\begingroup\$

Labyrinth, 8 bytes

Take that, Pyth...

?+
;,;!@

Try it online!

Explanation

The usual primer (stolen from Sp3000):

  • Labyrinth is 2D and stack-based. Stacks have an infinite number of zeroes on the bottom.
  • When the instruction pointer reaches a junction, it checks the top of the stack to determine where to turn next. Negative is left, zero is forward and positive is right.

What comes in really handy here is that Labyrinth has two different input commands, , and ?. The former reads a single byte from STDIN, or -1 at EOF. The latter reads an integer from STDIN. It does so skipping everything that isn't a number and then reads the first decimal number it finds. This one returns 0 at EOF, so we can't use it to check for EOF reliably here.

The main loop of the program is this compact bit:

?+
;,

With ? we read an integer (ignoring all letters), with + we add it to the running total (which starts out as one of the implicit zeroes at the stack bottom). Then we read another character with , to check for EOF. As long as we're not at EOF, the read character will be a letter which has a positive character code, so the IP turns right (from its point of view; i.e. west). ; discards the character because we don't need it and then we enter the loop again.

Once we're at EOF, , pushes a -1 so the IP turns left (east) instead. ; again discards that -1, ! prints the running total as an integer and @ terminates the program.

\$\endgroup\$
  • \$\begingroup\$ Awesome stuff Martin! \$\endgroup\$ – A Simmons Feb 17 '16 at 11:58
6
\$\begingroup\$

CJam, 13 bytes

Fixed to work with input without numbers thanks to Dennis! Also saved a byte by replacing the letters array with an array of ASCII above code point 64. And then another byte saved by Dennis!

q_A,s-Ser~]1b

Simple transliteration from letters to spaces, then eval and sum. Try it online.

\$\endgroup\$
6
\$\begingroup\$

MATL, 8 bytes

1Y4XXXUs

Try it online!

1Y4      % predefined literal: '\d+'
XX       % implicit input. Match regular expression. Returns a cell array of strings
         % representing numbers
XU       % convert each string to a double. Returns a numeric array
s        % sum of numeric array
\$\endgroup\$
5
\$\begingroup\$

Retina, 22 11

\d+
$0$*1
1

Try it online!

11 bytes (!) saved thanks to Martin!

Basically just decimal to unary then count the 1s.

\$\endgroup\$
  • 1
    \$\begingroup\$ I should probably make $0 implicit if a substitution starts with $*. It's a very common pattern and that would have let you beat Pyth. ;) \$\endgroup\$ – Martin Ender Feb 12 '16 at 15:44
  • \$\begingroup\$ @MartinBüttner While you're at it you could make the right character default to something too :O \$\endgroup\$ – FryAmTheEggman Feb 12 '16 at 15:46
  • \$\begingroup\$ hm, not a bad idea. I'll think about it. \$\endgroup\$ – Martin Ender Feb 12 '16 at 15:49
5
\$\begingroup\$

Japt, 2 bytes

Nx

Test it online!

How it works

N    // Implicit: N = (parse input for numbers, "strings", and [arrays])
x    // Sum. Implicit output.
\$\endgroup\$
  • \$\begingroup\$ I'm getting an error "Japt.stdout" must be sent to an HTMLElement \$\endgroup\$ – Downgoat Feb 12 '16 at 22:56
  • \$\begingroup\$ @Downgoat This happens occasionally; I'm not sure why. Reloading the page seems to fix this. \$\endgroup\$ – ETHproductions Feb 13 '16 at 1:00
5
\$\begingroup\$

JavaScript ES6, 35 bytes

s=>eval(s.replace(/\D+/g,'+')+'.0')

How it works

First, we replace each string of non-digits with "+". There are basically four different ways that this could end up:

1. 1b23c456   => 1+23+456
2. a1b23c456  => +1+23+456
3. 1b23c456d  => 1+23+456+
4. a1b23c456d => +1+23+456+

Cases 1 and 2 are taken care of already. But we somehow need to fix the last + so that it doesn't cause an error. We could remove it with .replace(/\+$,""), but that's too expensive. We could append a 0 to the end, but that would affect the last number if the string does not end with a +. A compromise is to append .0, which is both a valid number on its own and doesn't affect the value of other integers.

Here's a few other values that would work as well:

.0
-0
 +0
-""
-[]
0/10
0e-1
.1-.1

Alternate version, also 35 bytes

s=>s.replace(/\d+/g,d=>t+=+d,t=0)|t

Another alternate version, 36 bytes

s=>s.split(/\D/).map(d=>t+=+d,t=0)|t
\$\endgroup\$
4
\$\begingroup\$

Pyth, 12 11 10 bytes

ssM:z"\D"3
    z        autoinitialized to input()
   : "\D"3   split on non-digits
 sM          convert all elements of resulting array to ints
s            sum

Fortunately, s (convert to int) returns 0 when applied to the empty string, so I don't have to worry about the fact that split("a1b", "\D+") returns ["", "1", ""]. Similarly, split("a", "\D+") returns ["", ""].

This even allows me to split on every non-digit individually, since 1 + 0 + 0 + 0 + 0 + 2 is the same thing as 1 + 2.

Thanks to Thomas Kwa for a byte!

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

Gol><>, 4 bytes

iEh+

So short I need dummy text...

\$\endgroup\$
  • 3
    \$\begingroup\$ Perhaps you should explain your code with your extra space :) \$\endgroup\$ – nneonneo Feb 13 '16 at 17:56
4
\$\begingroup\$

Perl 6, 18 bytes

{[+] .comb(/\d+/)}
{[+] .split(/\D/)}

Usage:

my &code = {[+] .comb(/\d+/)}

say code 'a'; # 0
say code '0'; # 0
say code '5'; # 5
say code '10'; # 10
say code 'a0A'; # 0
say code '1a1'; # 2
say code '11a1'; # 12
say code '4dasQWE65asAs5dAa5dWD'; # 79
say code 'a1wAD5qw45REs5Fw4eRQR33wqe4WE'; # 97
\$\endgroup\$
3
\$\begingroup\$

Jelly, 6 bytes

&-ṣ-ḌS

Try it online!

How it works

&-ṣ-ḌS  Main link. Input: L (string)

&-      Take the bitwise AND of L's characters and -1.
        This attempts to cast to int, so '0' & -1 -> 0 & -1 -> 0.
        On failure, it returns the integer argument (if any), so 'a' & -1 -> -1.
  ṣ-    Split the resulting list at occurrences of -1.
    Ḍ   Convert each chunk from decimal to integer. In particular, [] -> 0.
     S  Compute the sum of the results.
\$\endgroup\$
3
\$\begingroup\$

Perl, 21 + 1 = 22 bytes

$_=eval join"+",/\d+/g

Requires the -p flag:

$ perl -pe'$_=eval join"+",/\d+/g' <<< 'a1wAD5qw45REs5Fw4eRQR33wqe4WE'
97
\$\endgroup\$
  • \$\begingroup\$ Does this work when there aren't any numbers? e.g. a? \$\endgroup\$ – FryAmTheEggman Feb 12 '16 at 16:20
  • \$\begingroup\$ @FryAmTheEggman Good question, I guess it will print nothing which in a numeric context is 0 ;-) \$\endgroup\$ – andlrc Feb 12 '16 at 16:28
3
\$\begingroup\$

Julia, 35 bytes

s->sum(parse,matchall(r"\d+","0"s))

This is an anonymous function that accepts a string and returns an integer. To call it, assign it to a variable.

We use matchall to get an array consisting of matches of the regular expression \d+, which are just the integers in the string. We have to tack on a 0 to the front of the string, otherwise for cases like "a", we'd be summing over an empty array, which causes an error. We then apply parse to each string match, which converts to integers, and take the sum.

\$\endgroup\$
  • \$\begingroup\$ parse can become int if you don't mind the deprecation warning. \$\endgroup\$ – Dennis Feb 12 '16 at 18:28
  • \$\begingroup\$ @Dennis I do though ._. \$\endgroup\$ – Alex A. Feb 12 '16 at 18:34
2
\$\begingroup\$

PHP, 64 bytes

<?php preg_match_all("/\d+/",$argv[1],$a);echo array_sum($a[0]);

Run it as

php -f filterOutAndAddUp.php <test_case>

https://eval.in/517817

\$\endgroup\$
  • \$\begingroup\$ Welcome to Programming Puzzles and Stack Exchange. This is a great answer (+1), however it could be improved by adding a code explanation and breakdown. Also, could you use <? instead of <?php? \$\endgroup\$ – wizzwizz4 Feb 12 '16 at 16:44
2
\$\begingroup\$

Javascript, 32 39 bytes

s=>eval((s.match(/\d+/g)||[0]).join`+`)

f=
s=>eval((s.match(/\d+/g)||[0]).join`+`)

F=s=>document.body.innerHTML+='<pre>f(\''+s+'\') -> '+f(s)+'\n</pre>'

F('a')
F('5')
F('10')
F('1a1')
F('11a1')
F('4dasQWE65asAs5dAa5dWD')
F('a1wAD5qw45REs5Fw4eRQR33wqe4WE')

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

Mathematica, 51 bytes

Total@ToExpression@StringCases[#,DigitCharacter..]&

Catching the wrong end of the verbose Mathematica builtins. 1 Byte off with the help of @DavidC

\$\endgroup\$
  • \$\begingroup\$ DigitCharacter .. will save 1 byte \$\endgroup\$ – DavidC Feb 12 '16 at 16:49
  • \$\begingroup\$ DigitCharacter doesn't work as written because it removes all the digits whereas we want to remove all the letters... \$\endgroup\$ – A Simmons Feb 12 '16 at 18:18
  • 1
    \$\begingroup\$ you are right. I was thinking of Total@ ToExpression@StringCases[#, DigitCharacter ..] & \$\endgroup\$ – DavidC Feb 12 '16 at 18:25
  • \$\begingroup\$ I see! Yeah that change saves a byte. \$\endgroup\$ – A Simmons Feb 12 '16 at 18:33
2
\$\begingroup\$

R, 46 43 bytes

sum(strtoi(strsplit(scan(,''),'\\D')[[1]]))

Explanation

                    scan(,'')                  # Take the input string
           strsplit(         ,'\\D')           # Returns list of all numeric parts of the string
                                    [[1]]      # Unlists to character vector
    strtoi(                              )     # Converts to numeric vector
sum(                                      )    # Sums the numbers

Sample run

> sum(strtoi(strsplit(scan(,''),'\\D')[[1]]))
1: a1wAD5qw45REs5Fw4eRQR33wqe4WE
2: 
Read 1 item
[1] 97

Edit: Replaced [^0-9] with \\D.

\$\endgroup\$
  • \$\begingroup\$ Welcome to Programming Puzzles and Code Golf. This is a great first answer; however it would be improved by adding a code explanation and breakdown, so we know how it works. \$\endgroup\$ – wizzwizz4 Feb 18 '16 at 13:22
1
\$\begingroup\$

PowerShell, 28 26 bytes

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

Takes input $args then does a regex -replace to swap the letters with +0, then pipes that to iex (short for Invoke-Expression and similar to eval).

PS C:\Tools\Scripts\golfing> .\filter-out-and-add-up.ps1 'a1wAD5qw45REs5Fw4eRQR33wqe4WE'
97

Alternatively

If you're OK with some extraneous output, you can do the following, also at 28 26 bytes:

$args-split"\D"|measure -s

This will take the input string $args and -split it into an array-of-strings on the non-numbers (removing them in the process). For example, 1a2b33 would turn into ['1','2','33']. We pipe that to Measure-Object with the -Sum parameter. Output would be like the below:

PS C:\Tools\Scripts\golfing> .\filter-out-and-add-up.ps1 'a1wAD5qw45REs5Fw4eRQR33wqe4WE'

Count    : 21
Average  : 
Sum      : 97
Maximum  : 
Minimum  : 
Property : 

Edit -- durr, don't need the [ ] in the regex since I'm no longer specifying a list of possible matches ...

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

Gema, 39 characters

<D>=@set{s;@add{${s;};$0}}
?=
\Z=${s;0}

Sample run:

bash-4.3$ gema '<D>=@set{s;@add{${s;};$0}};?=;\Z=${s;0}' <<< 'a1wAD5qw45REs5Fw4eRQR33wqe4WE'
\$\endgroup\$
1
\$\begingroup\$

Seriously, 13 bytes

,ú;û+@s`≈`MΣl

Try it online!

Explanation:

,ú;û+@s`≈`MΣl
,              push input
 ú;û+          push "abc...zABC...Z" (uppercase and lowercase English letters)
     @s        split on letters
       `≈`M    convert to ints
           Σ   sum
            l  length (does nothing to an integer, pushes 0 if an empty list is left, in the case where the string is all letters)
\$\endgroup\$
  • \$\begingroup\$ @Adnan Good catch - it outputs the empty list with a. Should be a one-byte fix. \$\endgroup\$ – Mego Feb 12 '16 at 17:53
1
\$\begingroup\$

Java, 70 bytes

s->{int n=0;for(String i:s.split("\\D+"))n+=Long.valueOf(i);return n;}
\$\endgroup\$
1
\$\begingroup\$

TI-Basic, 106 bytes

Works on TI-83/84 calculators!

Input Str1
"{0,→Str2
Str1+"N0→Str1
For(I,1,length(Ans
sub(Str1,I,1
If inString("0123456789",Ans
Then
Str2+Ans→Str2
Else
If ","≠sub(Str2,length(Str2),1
Str2+","→Str2
End
End
sum(expr(Ans
\$\endgroup\$
1
\$\begingroup\$

Clojure/ClojureScript, 35 bytes

#(apply +(map int(re-seq #"\d+"%)))
\$\endgroup\$
1
\$\begingroup\$

R, 50 bytes

Requires having gsubfn installed

sum(gsubfn::strapply(scan(,''),'\\d+',strtoi)[[1]])

Uses strtoi to coerce to numeric

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

Ruby 45 bytes

$*[0].split(/[a-z]/i).map(&:to_i).inject 0,:+

(First attempt at work, will revisit this)

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

POSIX sh + tr + dc, 27 25 bytes

dc -e "0d`tr -sc 0-9 +`p"

Converts any run of non-digits (including the terminating newline) to + operator, pushes two zeros onto the stack (in case input begins with non-digit), adds them all and prints the result. There may be an extra zero remaining at bottom of stack, but we don't care about that.

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

Lua, 51 Bytes

Pretty short for once! Even shorter than Java! The input must be a command-line argument for it to work.

a=0 arg[1]:gsub("%d+",function(c)a=a+c end)print(a)

Ungolfed

a=0                 -- Initialize the sum at 0
arg[1]:gsub("%d+",  -- capture each group of digits in the string
  function(c)       -- and apply an anonymous function to each of them
  a=a+c             -- sums a with the latest group captured
end)               
print(a)            -- output a
\$\endgroup\$
1
\$\begingroup\$

Bash + GNU utilities, 29

grep -Eo [0-9]+|paste -sd+|bc

If it is required to support input with no numbers (e.g. a), then we can do this:

Bash + GNU utilities, 38

1 byte saved thanks to @TobySpeight.

(grep -Eo [0-9]+;echo 0)|paste -sd+|bc
\$\endgroup\$
  • \$\begingroup\$ This prints nothing for input a. We are currently discussing whether that's valid or not. \$\endgroup\$ – Dennis Feb 13 '16 at 0:16
  • \$\begingroup\$ @Dennis. Ok. I added another version to cover both eventualities. \$\endgroup\$ – Digital Trauma Feb 13 '16 at 0:27
  • \$\begingroup\$ You could use ; instead of || to always add zero, for no harm. \$\endgroup\$ – Toby Speight Feb 15 '16 at 14:34
  • \$\begingroup\$ @TobySpeight Yes, thats good - thanks! \$\endgroup\$ – Digital Trauma Feb 15 '16 at 18:01
1
\$\begingroup\$

Python 2, 70 bytes

I am putting a Python answer just for fun.

import re
j=0
for i in map(int,re.findall('\d+',input())):j+=i
print j

Very simple and uses regex to find all the numbers in the input. Try it online!

\$\endgroup\$
  • 1
    \$\begingroup\$ In this context you have to use raw_input or switch to python3. A smaller version (py3, 56 bytes) : import re;print(sum(map(int,re.findall('\d+',input())))). \$\endgroup\$ – Dica Feb 18 '16 at 14:01
1
\$\begingroup\$

Oracle SQL 11.2, 105 bytes

SELECT NVL(SUM(TO_NUMBER(COLUMN_VALUE)),0)FROM XMLTABLE(('"'||regexp_replace(:1,'[a-zA-Z]','","')||'"'));

The regex convert alpha characters to ','

XMLTABLE create one row per item in the string using ',' as the separator.

SUM the rows to get the result.

NVL is needed to account for a string with no digit.

\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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