35
\$\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\$
9
  • 3
    \$\begingroup\$ Can we take input either as a string or a digit array? \$\endgroup\$
    – Shaggy
    Commented 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
    Commented 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\$ Commented Dec 19, 2022 at 11:04
  • 1
    \$\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
    Commented 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\$ Commented Jan 24, 2023 at 17:00

63 Answers 63

13
+50
\$\begingroup\$

Vyxal, 2 bytes

y∑

well.

Try it Online! | 1 byte with s

Explanation

y∑
y   Uninterleave, push two lists with every second and every second+1 digit
 ∑  Sum the first list
\$\endgroup\$
7
  • \$\begingroup\$ Wouldn’t that by 4 bytes? ∑ takes 3 bytes in UTF-8, 2 bytes in UTF-16 (but then y takes 2 bytes too). \$\endgroup\$
    – Lazy
    Commented Dec 18, 2022 at 17:11
  • \$\begingroup\$ @Lazy Vyxal uses a custom (SBCS) character set, which means it has 64 single-byte characters. \$\endgroup\$
    – math scat
    Commented Dec 18, 2022 at 18:54
  • \$\begingroup\$ Ah, good to know. \$\endgroup\$
    – Lazy
    Commented Dec 18, 2022 at 19:03
  • \$\begingroup\$ Why is the s solution not primary? \$\endgroup\$
    – Adám
    Commented Dec 24, 2022 at 21:51
  • \$\begingroup\$ @Adám I kinda want to have a 1-byte answer, but I feel like that's cheating \$\endgroup\$
    – math scat
    Commented Dec 25, 2022 at 14:18
10
\$\begingroup\$

R, 40 38 36 bytes

Edit: -2 bytes thanks to @Giuseppe.

\(x)sum(x%/%10^(nchar(x):0)%%10*1:0)

Attempt This Online!

\$\endgroup\$
2
  • \$\begingroup\$ 38 \$\endgroup\$
    – Giuseppe
    Commented Dec 18, 2022 at 15:43
  • \$\begingroup\$ @Giuseppe nice one, thanks! \$\endgroup\$
    – pajonk
    Commented Dec 18, 2022 at 19:23
9
\$\begingroup\$

JavaScript (ES6), 30 bytes

-1 by @l4m2

f=n=>n&&f(i=n/10|0)+i++%2*n%10

Try it online!


JavaScript (ES6), 31 bytes

f=n=>n?f(n/10|0)+i++%2*n%10:i=0

Try it online!

Commented

f = n =>            // f is a recursive function taking the input n
  n ?               // if n is not equal to 0:
    f(n / 10 | 0) + //   do a recursive call with floor(n / 10)
                    //   it's important to understand that:
                    //     1) n is defined in the local scope of f
                    //     2) i is defined in the global scope
                    //     3) we're not going to execute the code that
                    //        follows until the recursion stops and i
                    //        has been initialized
    i++ % 2 *       //   take the parity of i (increment it afterwards)
    n % 10          //   and multiply by the least significant decimal
                    //   digit of n
  :                 // else:
    i = 0           //   stop the recursion and initialize i to 0
\$\endgroup\$
1
  • \$\begingroup\$ 30 \$\endgroup\$
    – l4m2
    Commented Dec 18, 2022 at 11:45
9
\$\begingroup\$

Python 3, 28 37 32 30 35 bytes

lambda n:sum(map(int,str(n)[1::2]))

Assuming input is a string number

\$\endgroup\$
1
  • \$\begingroup\$ You might want to include a link, eg. ato \$\endgroup\$
    – math scat
    Commented Dec 18, 2022 at 14:10
8
\$\begingroup\$

Raku, 15 bytes

{sum m:g/.<(./}

Try it online!

Simple regex based sum of every other digit

\$\endgroup\$
8
\$\begingroup\$

Zsh, 33 bytes

for _ c (`fold -1`)let t+=c;<<<$t

Attempt This Online!

-3 bytes thanks to roblogic

Inputs as a string, because there is no way to input as a number in Zsh.

\$\endgroup\$
1
  • \$\begingroup\$ Not bad, I would have done, for j k (${(s::)1})((s+=k));<<<$s for 33 bytes... \$\endgroup\$
    – roblogic
    Commented Dec 19, 2022 at 10:31
8
\$\begingroup\$

Excel, 39 32 bytes

=SUM(--(0&MID(A1,2*ROW(A:A),1)))

enter image description here

\$\endgroup\$
2
  • 1
    \$\begingroup\$ You can get it down to 32 bytes by not worrying about how long the string is and handling the blank strings instead: =SUM(--(0&MID(A1,2*ROW(A:A),1))) \$\endgroup\$ Commented Dec 19, 2022 at 20:34
  • \$\begingroup\$ @EngineerToast very cool! \$\endgroup\$
    – jdt
    Commented Dec 20, 2022 at 2:07
8
\$\begingroup\$

Pip, 10 7 bytes

$+@SUWa

First pip answer, so don't sue me plz.

Try It Online!

Explanation

$+@SUWa
  @SUWa  Uninterweave a, take the second item of the two "every second element" lists 
$+       Sum the string

\$\endgroup\$
10
  • \$\begingroup\$ 9 bytes \$\endgroup\$
    – jezza_99
    Commented Dec 18, 2022 at 22:55
  • 1
    \$\begingroup\$ 7 bytes: $+@SUWa \$\endgroup\$
    – naffetS
    Commented Dec 19, 2022 at 1:28
  • 1
    \$\begingroup\$ Why would anyone sue you for being awesome? ;^) @Steffan, that's really clever! A couple alternate 7 byters for completeness: $+@RUWa or $+DQUWa. (Also, $+*SUWa and S$+*UWa technically output as a singleton list, but it looks the same without flags.) \$\endgroup\$
    – DLosc
    Commented Dec 19, 2022 at 5:04
  • \$\begingroup\$ @Steffan huh wow okaay. So @ can be used to convert a number to a string? \$\endgroup\$
    – math scat
    Commented Dec 19, 2022 at 12:47
  • 1
    \$\begingroup\$ @Steffan I think you meant to say S returns all but the first item (SUW = S UW). \$\endgroup\$
    – DLosc
    Commented Dec 19, 2022 at 18:22
8
\$\begingroup\$

Japt -hx, 3 bytes

Or 2 bytes with input as a string, or 1 byte with input as a digit array.

ì ó

Try it

ì ó     :Implicit input of integer
ì       :Convert to digit array
  ó     :Uninterleave
        :Implicit output of sum of last element
\$\endgroup\$
7
\$\begingroup\$

><>, 14 bytes

0i~i:c%@0(?n+!

Try it online!

Explanation

0               # init sum as 0
 i~             # discard an input
   i:           # duplicate an input
     c%@        # mod the copy by 12 and move down on stack
        0(?n    # if the other copy was negative, print the sum
            +!  # else add copy to sum and skip the next instruction
\$\endgroup\$
7
\$\begingroup\$

Perl -p, 18 bytes

s/.(.)/$\+=$1/ge}{

Try it online!

Input via STDIN.

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

Python 2, 39 32 bytes

-7 (pxeger suggested lambda)

lambda n:sum(map(int,`n`[1::2]))

TIO

EDIT: new test cases

\$\endgroup\$
1
  • 1
    \$\begingroup\$ You can shorten this by using a lambda: lambda n:sum(map(int,`n`[1::2])) \$\endgroup\$
    – pxeger
    Commented Dec 18, 2022 at 11:27
6
\$\begingroup\$

Ruby, 40 32 31 bytes

-8 bytes thanks to G B
-1 byte thanks to Armand Fardeau

->n{eval"#{n}".scan(/.(.)/)*?+}

Attempt This Online!

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

J, 15 bytes

All credit goes to Raul.

[:+/_2}.\,.&.":

Attempt This Online!

[:+/_2}.\,.&.":
         ,.&.":  NB. equivalent to ". ,. ": y, convert to digit list
    _2}.\        NB. behead each non-overlapping window of size 2
[:+/             NB. sum the resulting column

My original 19 bytes from 11 bytes

1(#.]*0 1$~#),.&.":

Updated to reflect challenge requirements. Thanks to Jonah for the modifications.

Attempt This Online!

1(#.]*0 1$~#),.&.":
             ,.&.":  NB. same as above
1(          )        NB. dyadic hook
           #         NB. use length of right arg to
      0 1$~          NB. reshape 0 1, reuses elements to create alternating 1's
    ]*               NB. multiply by the right arg
  #.                 NB. 1 #. y sums the result 
\$\endgroup\$
3
  • 1
    \$\begingroup\$ Pretty sure OP doesn't accept a list of digits as input (codegolf.stackexchange.com/questions/255650/…), so some kind of variant of 10&#.inv would be required to convert to digits beforehand \$\endgroup\$ Commented Dec 22, 2022 at 21:57
  • \$\begingroup\$ 1(#.]*0 1$~#),.&.": adapts your approach to the number input requirement. \$\endgroup\$
    – Jonah
    Commented Dec 22, 2022 at 23:17
  • 1
    \$\begingroup\$ Ah, I see. Appreciate it. Very smart use of &. here @Jonah. Will update. \$\endgroup\$
    – south
    Commented Dec 23, 2022 at 21:00
6
\$\begingroup\$

K (ngn/k), 13 12 bytes

+/(=\0&)#10\

Try it online!

  • 10\ convert (implicit) input integer to a list of its digits
  • (=\0&)# only keep elements at odd indices (0-indexed); literally, take the minimum of the digits and 0 (to zero-out every value), then use =\ (equals-scan) to generate a bit mask with 1s in odd indices and 0s in even ones
  • +/ calculate (and implicitly return) the sum
\$\endgroup\$
5
\$\begingroup\$

Pyth, 9 bytes

tssM%2+1z

Try it online!

      +1z    # Append '1' before the input
    %2       # Every 2nd element of
 ssM         # Map to integer and take sum
t            # Decrease by 1
\$\endgroup\$
5
\$\begingroup\$

Jelly, 5 bytes

D0ÐoS

Try it online!

Also 5 bytes

DŻm2S

Try it online!

Also also 5 bytes

Ds2SṪ

Try it online!

How they work

D0ÐoS - Main link. Takes an integer on the left
D     - Digits
  Ðo  - To digits in odd positions:
 0    -   Set them to 0
    S - Sum

DŻm2S - Main link. Takes an integer on the left
D     - Digits
 Ż    - Prepend a zero
  m2  - Take every second element
    S - Sum

Ds2SṪ - Main link. Takes an integer on the left
D     - Digits
 s2   - Slice into pairs
   S  - Sums
    Ṫ - Tail
\$\endgroup\$
1
  • 3
    \$\begingroup\$ Isn't D0ÐoS another language invented by Dennis? ;^) \$\endgroup\$
    – DLosc
    Commented Dec 19, 2022 at 5:11
5
\$\begingroup\$

Julia 1.0, 30 bytes

!n=sum(i->i-'0',"$n"[2:2:end])

Try it online!

\$\endgroup\$
5
\$\begingroup\$

Factor + math.unicode, 25 bytes

[ >dec <odds> 48 v-n Σ ]

Try it online!

       ! 548915381
>dec   ! "548915381"
<odds> ! "4958"
48     ! "4958" 48
v-n    ! { 4 9 5 8 }
Σ      ! 26
\$\endgroup\$
5
\$\begingroup\$

flax, 2 bytes

ΣẎ

Try It Online!

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

Dart (2.18.4), 92 77 bytes

f(n,[i=1])=>[for(;i<(n='$n').length;i+=2)int.parse(n[i])].reduce((v,e)=>v+e);
\$\endgroup\$
4
\$\begingroup\$

Python 3, 35 bytes

lambda n:sum(map(int,f'{n}'[1::2]))

Try it online!

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

Retina 0.8.2, 12 bytes

.(.?)
$1$*
.

Try it online! Link includes test cases. Takes input as a string because Retina has no integer types. Explanation:

.(.?)
$1$*

Convert alternate digits to unary, dropping the other digits.

.

Take the sum and convert back to decimal.

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

Charcoal, 7 bytes

IΣΦS﹪κ²

Try it online! Link is to verbose version of code. Explanation:

   S    Cast the input to string
  Φ     Filter characters where
     κ  Current index
    ﹪ ² Is odd
 Σ      Take the sum
I       Cast to string
        Implicitly print
\$\endgroup\$
4
\$\begingroup\$

pl – Perl One-Liner Magic Wand, 12 bytes

Use -o to loop over command line arguments. Global matching regexp returns every other character, in this case digit. By default List::Util::sum is imported, e(cho) its result. On the blog, hover the ▶ button, or the blue code box, to see the result:

pl -o 'e sum/.(.)/g' 10 101011 548915381 999999 2147483647 999999999
\$\endgroup\$
4
\$\begingroup\$

Haskell, 49 bytes

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

Try it online!

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

BQN, 18 bytes

1⊑·+˝⌊‿2⥊'0'-˜•Fmt

Anonymous tacit function that takes a number and returns a number. Try it at BQN online!

Explanation

1⊑·+˝⌊‿2⥊'0'-˜•Fmt
               •Fmt  Format as string
          '0'-˜      Subtract '0' character from each, giving a list of digits as numbers
     ⌊‿2⥊           Reshape into an array with two columns, dropping the last digit if
                     there is an odd number of digits
  ·+˝                Sum down each column
1⊑                   Take the element at index 1 (0-indexed) in the resulting list
\$\endgroup\$
4
\$\begingroup\$

sclin, 13 bytes

2/`1.: map +/

Try it here!

For testing purposes:

"548915381" ; n>o
2/`1.: map +/

Explanation

Prettified code:

2/` 1.: map +/
  • 2/` chunk into pairs
  • 1.: map get second element of each pair
  • +/ sum
\$\endgroup\$
4
\$\begingroup\$

Fig, \$3\log_{256}(96)\approx\$ 2.469 bytes

S]y

Try it online!

Port of Vyxal.

S]y
    # Uninterleave
 ]  # Get last
S   # Sum

Fig, \$6\log_{256}(96)\approx\$ 4.939 bytes

S-n2'0

Try it online!

My original answer before seeing Vyxal.

S-n2'0 # Input as a digit list
  n    # For every
   2   # Second item
    '  # Replace
     0 # With a 0
 -     # Subtract this from the original list
S      # Sum
\$\endgroup\$
4
\$\begingroup\$

Kotlin, 51 bytes

{it.map{it.code-48}.foldIndexed(0){i,a,c->i%2*c+a}}

No TIO link as it doesn't have an updated version, ATO borks with it for some reason.

{it.map{it.code-48}.foldIndexed(0){i,a,c->i%2*c+a}} // String input
{                                                 } // Lambda expression
 it.map{it.code-48}                                 // Subtract 48 from each char, turning the string into a list of digits
                   .foldIndexed(0){i,a,c->       }  // Fold over the list, starting with 0. i is the index, a is accumulator, and c is the digit
                                          i%2*c     // Multiply the current digit by the index mod 2. If it is even, it resolves to 1*c, otherwise 0*c
                                               +a   // Add to accumulator
\$\endgroup\$
1
  • \$\begingroup\$ 43 bytes if you map with the index: {it.mapIndexed{i,a->i%2*(a.code-48)}.sum()} \$\endgroup\$
    – user
    Commented Dec 24, 2022 at 20:24

Your Answer

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

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