23
\$\begingroup\$

Given a non-negative integer, return the absolute difference between the sum of its even digits and the sum of its odd digits.

Default Rules

  • Standard Loopholes apply.

  • You can take input and provide output by any standard Input / Output method.

  • You may take input as a String, as an Integer or as a list of digits.

  • This is , so the shortest code in bytes in every language wins!

Test Cases

Input ~> Output

0 ~> 0 (|0-0| = 0)
1 ~> 1 (|1-0| = 1)
12 ~> 1 (|2-1| = 1)
333 ~> 9 (|0-(3+3+3)| = 9)
459 ~> 10 (|4-(5+9)| = 10)
2469 ~> 3 (|(2+4+6)-9| = 3)
1234 ~> 2 (|(2+4)-(1+3)| = 2)
\$\endgroup\$
6
  • 1
    \$\begingroup\$ May we take input as list of ints? \$\endgroup\$
    – Adám
    Jul 10, 2017 at 16:43
  • 5
    \$\begingroup\$ @Mr.Xcoder That wouldn't be too trivial. It makes the challenge unnecessarily complicated and is an arbitrary requirement that adds bytes. \$\endgroup\$
    – Okx
    Jul 10, 2017 at 16:46
  • 5
    \$\begingroup\$ @Mr.Xcoder Don't make chameleon challenges. The most important sentence you might want to look at here is Combining two or more unrelated core challenges into one — consider splitting the challenge up into separate challenges or dropping unnecessary parts \$\endgroup\$
    – Okx
    Jul 10, 2017 at 16:51
  • 1
    \$\begingroup\$ I have changed the rules @Okx. Taking as a list of digits is now allowed. I still don't think it would make it to fluffy though. \$\endgroup\$
    – Mr. Xcoder
    Jul 10, 2017 at 16:55
  • \$\begingroup\$ 333 ~> 9 (|(3+3+3)-0| = 9) should be 0-(3+3+3), though the outcome is the same. \$\endgroup\$ Jul 11, 2017 at 20:37

56 Answers 56

1
2
1
\$\begingroup\$

TI-BASIC, 11 6 bytes

abs(sum(Anscos(πAns

Takes input as a list. i²^Ans saves two bytes over (-1)^Ans because we don't need the parentheses.

abs(sum(Anscos(πAns
           cos(πAns                  1 for evens, -1 for odds
        Ans                          Multiply by original list
abs(sum(                             Sum the list and take absolute value, which also
                                     fixes rounding errors from cos(.
\$\endgroup\$
1
\$\begingroup\$

J, 14 bytes

|-/(2&|+//.[),

Try it online!

explanation

|                absolute value of
 -/              the difference between
                 the items on the list returned by this fork
   (2&|          is an item odd? (1 for yes, 0 for no)
       +//.      the "key" verb /. which partitions on above (even / odd) then sums
           [)    identity, ie, the list of digits passed
             ,   turn it into a list (to handle 1 element case)
\$\endgroup\$
1
\$\begingroup\$

Tcl, 55 bytes

lmap e $V {incr s [expr $e*-1**$e]}
puts [expr abs($s)]

Try it online!

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

Ruby, 45 bytes

Function; Full number

->n{s=0
n.digits.map{|x|s+=x%2>0?x:-x}
s.abs}

Try it online!

Ruby, 38 bytes

Function; List of digits

->n{s=0
n.map{|x|s+=x%2>0?x:-x}
s.abs}

Try it online!

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

Rust, 73 bytes

fn f(mut a:i32)->i32{let mut s=0;while a>0{s+=a%10*(a%2*2-1);a/=10}s.abs()}

Try it online!

Rust, 68 bytes

This takes a slice of digits rather than an integer.

fn z(a:&[i32])->i32{a.iter().map(|x|x*(x%2*2-1)).sum::<i32>().abs()}

Try it online!

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

J, 11 bytes

Credit to Uriel’s APL solution

1|@#.[*_1^]

Try it online!

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

Pyth, 16 12 11 10 8 bytes

.asm*^tZ

Try it online!


How?

.asm*^tZ – Full program. Q = input.
   m*^tZ – Raise -1 to the power of each d in Q and multiply by d.
  s      – Sum.
.a       – Absolute value.
\$\endgroup\$
1
\$\begingroup\$

Vyxal, 6 bytes

u$eÞ•ȧ

Try it Online!

Port of Jelly.

u$eÞ•ȧ
u$e     # Raise -1 to the power of each
   Þ•   # Dot product with the input
     ȧ  # Absolute value
\$\endgroup\$
1
\$\begingroup\$

Ly, 24 bytes

0spSy[f:2%2*,*l+sp,]lar-

Try it online!

This is pretty brute force, it just adds or subtracts each number to an accumulator depending on whether it's odd or even. The post-loop bit is the shortest way to get an abs() in Ly I could think of.

0sp                       - initialize the backup cell to 0, clear stack
   S                      - convert the number on STDIN to digits on the stack
    y                     - push the number of digits onto the stack
     [f           ,]      - loop decrementing the digit count, stop on 0
       :                  - duplicate the next digit
        2%                - modulo by 2 to get odd/even
          2*,             - do "(x*2)-1" to map 1 to 1, and 0 to -1
             *            - multiple the digit by that 1/-1
              l+sp        - add to backup cell, pop from stack
                    l     - load the final difference from accumulator
                     a    - sort stack (has a 0 and the accumulator val)
                      r   - reverse stack
                       -  - subtract to flip the sign if difference was <0

The programs with a positive number on the stack, which is printed automatically.

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

Desmos, 24 bytes

f(l)=abs(total(l(-1)^l))

Input as a list of digits.

Try It On Desmos!

Try It On Desmos! - Prettified

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

Nibbles, 6 bytes (12 nibbles)

!=+$*+|$%$~~

Calculates the absolute difference between the sum of all digits and twice the sum of the odd digits.

!=+$*+|$%$~~
!=              # absolute difference between
  +             #   sum of 
   $            #   input
                # and
     +          #   sum of 
       $        #   input 
      |         #   filtered for nonzero when
        %$      #     modulo
          ~     #     2 (default for modulo)
    *           #   multiplied by
           ~    #   2 (default for multiplication)  

enter image description here

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

MathGolf, 6 bytes

b▬m*Σ±

Port of @Dennis' Jelly answer.

Input as a list of digits.

Try it online.

Explanation:

b      # Push -1
 ▬     # Take -1 to the power of each integer in the (implicit) input-list
  m*   # Multiply the values at the same positions of this list and the (implicit) input
    Σ  # Sum this list together
     ± # Get its absolute value
       # (after which the entire stack is output implicitly as result)
\$\endgroup\$
1
\$\begingroup\$

Japt, 8 bytes

üv mx ra

Try it

Takes input as a digit array

üv mx ra     :Implicit input of digit array
ü            :Group by
 v           :  Divisible by 2?
   m         :Map
    x        :  Sum
      r      :Reduce by
       a     :  Absolute difference
\$\endgroup\$
1
\$\begingroup\$

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

AS*^N1

Try it online!

Port of MathGolf. Surprisingly, beats Jelly.

AS*^N1 # Input as list of digits
    N1 # -1
   ^   # To the power of each in the input
  *    # Multiply the list of 1s and -1s by each digit
 S     # Sum
A      # Absolute value
\$\endgroup\$
1
\$\begingroup\$

J-uby, 33 bytes

:partition+:odd?|:*&:sum|+:-|:abs

Attempt This Online!

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

Pip, 9 bytes

AB$+g*vEg

Try It Online!

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

Arturo, 26 bytes

$=>[abs∑map&'x->x*^0-1x]

Try it

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

Thunno, \$ 9 \log_{245}(96) \approx \$ 7.41 bytes

D1n@z*SZA

Attempt This Online! or verify all test cases.

Explanation

D1n@z*SZA  # Implicit input        [1, 2, 3, 4]
D          # Duplicate             [1, 2, 3, 4], [1, 2, 3, 4]
 1n@       # Push -1 ** each       [1, 2, 3, 4], [-1, 1, -1, 1]
    z*     # Multiply elementwise  [-1, 2, -3, 4]
      S    # Sum this list         2
       ZA  # Absolute value        2
           # Implicit output
\$\endgroup\$
0
\$\begingroup\$

C#, 59 bytes

Math.Abs(a.Where(x=>(x%2<1)).Sum()-a.Where(x=>x%2>0).Sum())
\$\endgroup\$
1
  • \$\begingroup\$ You may want to add some kind of explanation for this. Just for the people who don't know C. As it is, it's kind of just the code. \$\endgroup\$
    – Gryphon
    Jul 11, 2017 at 12:57
0
\$\begingroup\$

CJam, 16 14 Bytes

q{si_W\#*}%:+z

Try it online

q{si_W\#     e# Take -1 to power of digit
*}%          e# Multiply result by digit 
:+z          e# Sum altered digits and return the absolute value
\$\endgroup\$
0
\$\begingroup\$

Common Lisp, 52 bytes

(defun f(x)(abs(loop as i in x sum(*(expt -1 i)i))))

Try it online!

Translation of Dead Possum answer.

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

java , 314 bytes

public  static int f (String s)
{
    char [] m =s.toCharArray();
    int o=0 ,e=0; 
    for(int i =0 ;i<m.length;i++)
    { int n=(int)m[i]-48;
    if(n%2==0)
        e+=n;
    else 
        o+=n;
    }
    return abs(e-o);


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

Java (OpenJDK 8), 64 bytes

Takes n as int input, uses mod 10 and div 10 to sum from least significant digit and return Absolute value when done.

n->{int r=0;for(;n>0;n/=10)r+=n%2>0?-n%10:n%10;return r<0?-r:r;}

Try it online

\$\endgroup\$
3
  • 1
    \$\begingroup\$ Welcome to PPCG! Your TIO link doesn't seem to match your code, would you mind updating it? \$\endgroup\$ Jul 11, 2017 at 15:26
  • 1
    \$\begingroup\$ That TIO is actually my answer, but to another question! O_o \$\endgroup\$ Jul 11, 2017 at 19:01
  • \$\begingroup\$ Fixed! and thanks for the welcome... \$\endgroup\$
    – tfantonsen
    Jul 12, 2017 at 14:37
0
\$\begingroup\$

Bash, 51 bytes

Full program; Full number

Or "bash with awk" for the pedantics.

grep -o .|awk '{a+=$0%2?$0:-$0}END{print a<0?-a:a}'

Try it online!

Explanation

grep -o .| # every /./ on a new line
awk '{
            // a is initialized to 0 cuz awk lol
  a+=$0%2   // Is odd?
    ?$0:-$0 // true -> add +, false -> add -
}
END{
  print a<0?-a:a // to absolute value
}'
\$\endgroup\$
0
\$\begingroup\$

AWK, 35 bytes

Full program; List of digits

{a+=$0%2?$0:-$0}END{print a<0?-a:a}

Try it online!

Technically not the same as my other answer. I still think that one is better because using a list of digits feels cheap.

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

APL NARS 26 chars

{∣(+/-a)+2×+/(2∣a)/a←⍎¨⍕⍵}

test

  f←{∣(+/-a)+2×+/(2∣a)/a←⍎¨⍕⍵}
  f¨0 1 12 333 459 2469 1234
0 1 1 9 10 3 2
\$\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.