34
\$\begingroup\$

I have a number like this:

n = 548915381

The output should be the sum of every second digit of that number. In this case 26:

4+9+5+8 = 26

Rules:

  • This is a , so the shortest code in bytes wins.
  • The input consists only of numbers bigger than 10 (at least 2 digits) but smaller than a 32-bit integer.
  • The input will be a number, not a string

Test cases:

Input Output
10 0
101011 1
548915381 26
999999 27
2147483647 29
999999999 36
\$\endgroup\$
7
  • 2
    \$\begingroup\$ Can we take input either as a string or a digit array? \$\endgroup\$
    – Shaggy
    Dec 18, 2022 at 17:42
  • 3
    \$\begingroup\$ Technically, it should be a number. Take whichever is closer in said programming language \$\endgroup\$
    – S-Flavius
    Dec 18, 2022 at 18:17
  • 4
    \$\begingroup\$ While we advise against accepting an answer in the first place to [code-golf] challenges, as it gives the impression that the challenge is "over", if you do accept an answer, it's recommended to wait longer than a day, to give everyone enough opportunity to participate. \$\endgroup\$ Dec 19, 2022 at 11:04
  • \$\begingroup\$ The formulation is ambiguous. At first, I thought the first two outputs would be 1 and 3, for example… The chosen order defining "every second digit" isn't "natural" in programming terms. \$\endgroup\$
    – PhiLho
    Dec 21, 2022 at 8:08
  • 1
    \$\begingroup\$ A specification shouldn't be inferred from test cases. Since there's only one input for which it's different, I actually assumed it takes digits from right to left until I saw the first answer! \$\endgroup\$ Jan 24 at 17:00

57 Answers 57

1
2
4
\$\begingroup\$

Octave, 31 bytes

@(s)sum(num2str(s)(2:2:end)-48)

Try it online!

This converts the number to a string, sums up the character codes in the string, then subtracts the ASCII code for 0 (48) from each character.

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

C (gcc), 35 bytes

i;f(n){n=n?f(i=n/10)+i++%2*n%10:0;}

Try it online!

Port of js solution

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

Haskell, 49 bytes

f s=sum[read[x]|(i,x)<-zip[0..]$show s,mod i 2>0]

Try it online!

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

05AB1E, 5 bytes

2ι`SO

Try it online!

Explanation

2ι`SO  # Implicit input                          TOP OF STACK:
2ι     # Get every second character              ["58131", "4958"]
  `    # Dump onto the stack                     "4958"
   S   # Cast to a list of characters            ["4", "9", "5", "8"]
    O  # Sum it up (implicit cast to integer)    26
\$\endgroup\$
3
\$\begingroup\$

jonesforth, 104 bytes

: F DUP UWIDTH 1 AND IF BASE @ / THEN 0 SWAP BEGIN BASE @ /MOD -ROT + SWAP BASE @ / DUP NOT UNTIL DROP ;

Less obfuscated version:

: F
    \ make sure we have an even number of digits
    DUP UWIDTH
    1 AND
    IF BASE @ / THEN

    0 SWAP
    ( accumulator value )
    BEGIN
        \ add the smallest digit to the accumulator
        BASE @ /MOD ( acc rem quot )
        -ROT + SWAP
        \ discard the new smallest digit
        BASE @ / ( acc v )
        \ loop until the value is 0
        DUP NOT
    UNTIL
    DROP
;

This answer needs UWIDTH, which gforth doesn't have, so I specified jonesforth because it definitely works on jonesforth.

It compiles to 124 bytes, which drops to 116 if you have constants defined for 0 and 1. On a 16 bit forth it would theoretically be half that. Also it has the added bonus of working in any base between 2 and 36.

\$\endgroup\$
1
  • 1
    \$\begingroup\$ Welcome to Code Golf, and nice first answer! \$\endgroup\$
    – The Thonnu
    Apr 2 at 11:56
2
\$\begingroup\$

Desmos, 61 bytes

D=floor(logk)
f(k)=∑_{n=0}^Dmod(n+D,2)mod(floor(k/10^n),10)

Try It On Desmos!

Try It On Desmos! - Prettified

There must be some better way to do this other than separating out the D=floor(logk) lol.

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

Acc!!, 176 bytes

48
Count i while _%60/48 {
_+_%60*59-2880+0*N+N
}
_/60
Count d while _/10^d {
Count i while 9/(_/10^d)*(d-i+1) {
Write _/10^(d-i)%10+48
}
}
_+1
Count z while 1/_ {
Write 48
2
}

Try it online!

Explanation

As often happens with Acc!!, the majority of the code is taken up by decimal I/O.

### INPUT AND COMPUTATION ###
# Load a spurious 0 digit into the accumulator
48
# Loop while we just read a digit character and not a newline/eof 
Count i while _%60/48 {
  # Add the digit represented by the character code in _%60 to the running tally in _/60
  _-_%60+60*(_%60-48)
  # Read the next character and do nothing with it
  _+0*N
  # Read the next character and store it in _%60
  _+N
}
# Set the accumulator to the value in _/60
_/60

### OUTPUT ###
# Figure out how many digits the accumulator value has
Count d while _/10^d {
  # Once we're on the leftmost digit, loop a number of times equal to the number of digits
  Count i while 9/(_/10^d)*(d-i+1) {
    # Output each digit from most significant to least significant
    Write _/10^(d-i)%10+48
  }
}
# But if the value was zero, this didn't output anything, so...
# Convert 0 -> 1, other values to numbers greater than 1
_+1
# Loop while accumulator is 1
Count z while 1/_ {
  # Write a 0 character
  Write 48
  # Set accumulator to 2 to break out of the loop
  2
}
\$\endgroup\$
2
\$\begingroup\$

Brachylog, 8 6 bytes

ġ₂z₁t+

Try it online!

-2 bytes thanks to @DLosc.

Explanation

ġ₂         Group consecutive digits into sublists of 2 elements
  z₁       Zip
     t     Tail
       +   Sum
\$\endgroup\$
0
2
\$\begingroup\$

jq -R, 28 bytes

[scan("..")|tonumber%10]|add

Try it online!

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

Arturo, 32 29 bytes

$[n][0loop digits n[a,b][+b]]

Try it

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

vemf, 25 8 bytes

-17 bytes thanks to language creator

Well this is a fun one.

ª‼│%2╕º+

try it online - uses 8472 as an example

Explanation

ª‼│%2╕º+

ª        ' convert to string
 ‼       ' repeat each character...
  │%2    ' (index mod 2) times
     ╕º  ' convert them back to numbers
       + ' sum

Old answer (25 bytes):

{`l←╢αª♣ó╕=_1·αª╕‼.l,-:48+

try it online

Explanation

{`l←╢αª♣ó╕=_1·αª╕‼.l,-:48+

{                          ' define function. (closing } optional)

 `l←                       ' make a list:
    ╢                      ' (group next 9 characters)
         ╕                 ' for each element of
       ♣                   ' the domain of
     αª                    ' left argument as string,
        ó                  ' is (-1)^x
          =_1              ' equal to -1?
             ·             ' discard the return value

              স          ' for each character,
                 ‼         ' repeat it
                  .l       ' by the corresponding list entry
                    ,      ' concatenate the resulting list
                     -:48  ' subtract 0x30 from each entry, so 1 maps to 0x01 etc
                         + ' sum
\$\endgroup\$
3
  • \$\begingroup\$ In your explanation of in the 8-byte solution, do you mean 'index' (position in the string) instead of 'codepoint' (character value)? \$\endgroup\$ Apr 2 at 16:50
  • 1
    \$\begingroup\$ @DominicvanEssen Yes, but all does is group the next two characters, equivalent to (%2). \$\endgroup\$
    – merrybot
    Apr 2 at 17:07
  • \$\begingroup\$ Ah, that makes sense now. Thanks. \$\endgroup\$ Apr 2 at 17:09
2
\$\begingroup\$

Bash +coreutils, 29 bytes

fold -2|cut -c2|paste -sd+|bc

Try it online!


Alternatives (38b, 46b)

echo `sed -E s'/(.)([0-9])/\2+/g'`0|bc
for z in `fold -1`;{((t+=i++%2?z:0));};echo $t
\$\endgroup\$
1
\$\begingroup\$

Python 3, 41 bytes

lambda n:sum(int(i)for i in str(n)[1::2])

Try it online!

\$\endgroup\$
12
  • 1
    \$\begingroup\$ And if you try and golf this one down, it's just going to converge into that answer. \$\endgroup\$
    – The Thonnu
    Dec 18, 2022 at 13:03
  • 2
    \$\begingroup\$ @TheThonnu Exactly the reason why I didn’t use it. \$\endgroup\$ Dec 19, 2022 at 5:11
  • 2
    \$\begingroup\$ You can use str(n) instead of `n` to achieve the same thing. And still, you haven't even removed the very unnecessary square brackets. \$\endgroup\$
    – The Thonnu
    Dec 19, 2022 at 9:35
  • 1
    \$\begingroup\$ Since you insist, I’ll remove them. Note that using map will effectively make this a port of the other answer which is why I won’t use it. \$\endgroup\$ Dec 19, 2022 at 11:19
  • 2
    \$\begingroup\$ @TheThonnu one last thing; please be a bit kinder when giving golfing suggestions to others; most people will act more hostile than me when receiving golfing suggestions in such a tone. \$\endgroup\$ Dec 20, 2022 at 12:06
1
\$\begingroup\$

Python 3, 45 bytes

e=lambda n:sum([int(x)for x in str(n)[1::2]])

Try it online!

\$\endgroup\$
2
  • 1
    \$\begingroup\$ You can save 10 bytes with: Try it online! \$\endgroup\$ Dec 21, 2022 at 11:41
  • \$\begingroup\$ Anonymous function submissions are allowed, so you can remove e= to save 2 bytes \$\endgroup\$ Jun 29 at 12:26
1
\$\begingroup\$

Pyt, 7 bytes

ąĐƩ⇹ƧƩ-

Try it online!

ąĐƩ⇹ƧƩ-
ą         implicit input (n); convert n to array of digits
 Đ        duplicate top of stack
  Ʃ       sum the digits of n
    ⇹     swap the top two items on the stack
     ƧƩ   sum every other digit of n, starting with the first
      -   subtract; implicit print
\$\endgroup\$
1
\$\begingroup\$

Prolog (SWI), 53 bytes

\X:-get(_),get(C),C>0,Z is X+C-48,\Z;write(X).
:- \0.

Try it online!

Full program.

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

Nibbles, 4.5 bytes

+`%~>>`@~

Attempt This Online!

Explanation

+   Sum of
`%~  select every second element, starting at first, in
>>    remove first element of
`@~    base 10 digits of
        input
\$\endgroup\$
1
\$\begingroup\$

Thunno, \$ 6 \log_{256}(96) \approx \$ 4.94 bytes

dZlAKS

Attempt This Online!

Explanation:

dZlAKS  # Implicit input
d       # Cast to digits
 Zl     # Uninterleave
   AK   # Get last element
     S  # Sum this list
        # Implicit output      
\$\endgroup\$
1
\$\begingroup\$

JavaScript, 42 bytes

Without recursion:

n=>[...''+n].reduce((s,n,i)=>s+=i%2&&+n,0)

Try it:

f=n=>[...''+n].reduce((s,n,i)=>s+=i%2&&+n,0)

console.log(f(10))         // 0
console.log(f(101011))     // 1
console.log(f(548915381))  // 26
console.log(f(999999))     // 27
console.log(f(2147483647)) // 29
console.log(f(999999999))  // 36

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

Java 8 (OpenJDK 8), 110 112 bytes

-2 bytes thanks to @ceilingcat !

Solution using only a single inline Stream, and using a 2-cell array as the accumulator of the reduce to carry both the sum and the index of the current cell.

This could easily be outgolfed by a more classic Java solution.

n->(n+"").chars().mapToObj(e->new int[]{e-48}).reduce(new int[2],(a,b)->new int[]{a[0]+a[1]%2*b[0],++a[1]})[0]

Try it online!

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

Lua, 43 bytes

a=0(...):gsub('.(.)',load'a=...+a')print(a)

Try it online!

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

Kamilalisp, 38 bytes (APL SBCS)

λ x \⌿⊙← + \⍠¨ *&[$(^mod 2)#0]\⌹⊙ 10 x

Attempt This Online!

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

Racket, 112 bytes

((λ(l)(for/sum([i(range(length l))]#:when(odd? i))(-(char->integer(list-ref l i))48)))(string->list(~a(read))))

Try it online!


Explanation

Creates an anonymous function that receives user input as a list of characters. It then iterates through the length of the list. If the index is an odd number, we transform the current charater into a digit and add it to the sum.

((lambda (lst)
   (for/sum ([index (range (length lst))]
             #:when (odd? index))
     (- (char->integer (list-ref lst index)) 48)))
 (string->list (~a (read))))

The mysterious "89" with no input

If you supply this program with no input, you will notice that the final sum would be 89.

That is because we convert the result of read directly into a string.

(~a (read))

When there is no input, the read function returns #<eof>. Our code converts the #<eof> symbol to a string, "#<eof>". Then it loops through all the characters that have odd indices, giving us a list of '(#\< #\o #\>). After that, the characters are converted into ASCII numbers. Since the ASCII value of "0" is 48, we subtract 48 from the result:

; (x - 48 becomes y)
'((#\<  12)
  (#\o  63)
  (#\>  14))

The numbers are then summed together to get 89.


Have a wonderful week ahead!

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

Thunno 2 S, 1 byte

^

Try it online!

Thunno 2, 2 bytes

^S

Try it online!

Explanation

^S  # Implicit input  ->  548915381
^   # Uninterleave    ->  [5,8,1,3,1], [4,9,5,8]
 S  # Sum the list    ->  [5,8,1,3,1], 26
    # Implicit output
\$\endgroup\$
0
\$\begingroup\$

Matlab, 166 bytes

n = input('Input : ', 's');
d = str2double(regexp(n,'\d','match')); %convert n to a unidimensional matrix 
total = 0; %stores total sum
    for i = 2:2:length(d) %traverse the unidimensional matrix [ vector ]
        total = total + d(i); %sum of every second n
    end
disp(['Output : ', num2str(total)]);

enter image description here

\$\endgroup\$
1
  • 2
    \$\begingroup\$ Welcome to Code Golf! This site is for competitive programming, so we require answers to aim to shorten their code as much as possible (such as removing whitespace, getting rid of input prompts, etc.). Make sure to read our tips questions if you want some hints! \$\endgroup\$ Dec 23, 2022 at 17:38
0
\$\begingroup\$

Java 19, 100 bytes

Partial program assuming n is the given number:

var m=0;var s=String.valueOf(n);for(var i=1;i<s.length();i+=2)m+=s.charAt(i)-48;System.out.print(m);

Full program using standard input:

interface A{
    static void main(String[]a){
        var n=Integer.parseInt(a[0]);
        //
        var m=0;
        var s=String.valueOf(n);
        for(var i=1;i<s.length();i+=2)m+=s.charAt(i)-48;
        System.out.print(m);
        //
    }
}
\$\endgroup\$
0
\$\begingroup\$

Commodore BASIC (C64/128, C16/+4, VIC-20, PET, THEC64 Mini/THEC64/THEVIC20) - 88 BASIC Bytes

0 inputn$:iflen(n$)=0thenend
1 iflen(n$)<2orval(n$)<9then3
2 fori=2tolen(n$)step2:n=n+val(mid$(n$,i,1)):next
3 printn

A quick explanation

  • Line zero waits for an input; if there is no input, then the program is ended
  • Line one checks if the length of the input is 1 character, or the value is fewer than 9, if so, we branch to line 3
  • Line two iterates over the string from the second character, and each second character thereafter until the end of the string. The value of each is added to n (which will be zero before the for/next loop).
  • Line 3 outputs the total sum on n

Sum every second digit in a number, Commodore C64

\$\endgroup\$
1
2

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

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