32
\$\begingroup\$

Implement a function diff that takes as input three integers x, y, and z. It should return whether subtracting one of these numbers from another gives the third.

Test cases:
diff(5, 3, 2) yields True because 5 - 3 = 2
diff(2, 3, 5) yields True because 5 - 3 = 2
diff(2, 5, 3) yields True because 5 - 3 = 2
diff(-2, 3, 5) yields True because 3 - 5 is -2
diff(-5, -3, -2) # -5 - -2 is -3
diff(2, 3, -5) yields False
diff(10, 6, 4) yields True because 10 - 6 = 4
diff(10, 6, 3) yields False

You don't have to name the function, you may implement default input methods the examples above are not a strict guideline.

\$\endgroup\$
10
  • 6
    \$\begingroup\$ This is a reasonable challenge, but there's no need to restrict it to Python or functions. In general, such restrictions are frowned upon because they limit participation. Also, you should include some test cases. \$\endgroup\$
    – xnor
    Feb 7, 2016 at 9:37
  • \$\begingroup\$ Hey I fixed it a little. Hope this suffices! \$\endgroup\$
    – Mir
    Feb 7, 2016 at 9:45
  • 2
    \$\begingroup\$ Looks better! I still strongly recommend allowing the default input methods, in particular programs, because some languages don't have functions. And, allowing functions to have another name or no name. \$\endgroup\$
    – xnor
    Feb 7, 2016 at 9:48
  • \$\begingroup\$ The first and last paragraphs are now conflicting, so just to double check - do we have to write a function or are full programs okay? \$\endgroup\$
    – Sp3000
    Feb 7, 2016 at 10:03
  • \$\begingroup\$ full programs are fine, I want to impose as few restrictions as possible except that the default input methods are followed. ef the python3 examples is neat! \$\endgroup\$
    – Mir
    Feb 7, 2016 at 10:18

28 Answers 28

51
\$\begingroup\$

Python 3, 21 bytes

lambda*l:sum(l)/2in l

If two numbers add to the other, the sum of all three will be double that other number, so half the sum will be an element of the list. Python 3 is needed to avoid floor-division, unless the numbers are given like 3.0 rather than 3.

\$\endgroup\$
14
\$\begingroup\$

Jelly, 5 3 bytes

Thanks to @Sp3000 for saving two bytes!

Code, uses quite the same algorithm as @xnor's great answer:

SfḤ

Explanation:

S     # Sum of the argument list
  Ḥ   # Double the list
 f    # Filter, remove everything that isn't equal to the sum of the list

This gives [] as falsy, and anything else as truthy.

Try it online!

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

ES6, 31 bytes

(a,b,c)=>a+b==c|b+c==a|c+a==b

Add 5 bytes if you need to name the function diff.

Edit: Saved 2 bytes thanks to @Alex L.

\$\endgroup\$
2
  • \$\begingroup\$ You can save two bytes by replacing || with | (I think) \$\endgroup\$
    – hyper-neutrino
    Feb 9, 2016 at 3:16
  • \$\begingroup\$ @AlexL. Ah right I was too hung up on having to return Booleans. \$\endgroup\$
    – Neil
    Feb 9, 2016 at 8:59
4
\$\begingroup\$

JavaScript ES6, 38 34 33 bytes

x=>x.some(a=>2*a==x[0]+x[1]+x[2])

Very simple anonymous function, and borrows from the Python answer. Takes input x as an array; returns true or false. Bytes shaved to Molarmanful and jrich

A 38-byte program, taking each number as an argument:

(a,b,c)=>[a,b,c].some(t=>t==(a+b+c)/2)
\$\endgroup\$
4
  • \$\begingroup\$ Try x=>x.some(a=>a==eval(x.join`+`)/2), which saves 4 bytes. \$\endgroup\$ Feb 7, 2016 at 23:29
  • \$\begingroup\$ @ӍѲꝆΛҐӍΛПҒЦꝆ Thanks! Nice trick. \$\endgroup\$ Feb 7, 2016 at 23:34
  • \$\begingroup\$ x=>x.some(a=>2*a==x[0]+x[1]+x[2]) seems to work. \$\endgroup\$
    – jrich
    Feb 9, 2016 at 2:42
  • \$\begingroup\$ @jrich Thanks! Nice trick! \$\endgroup\$ Feb 9, 2016 at 2:44
3
\$\begingroup\$

Oracle SQL 11.2, 49 bytes

SELECT 1 FROM DUAL WHERE(:1+:2+:3)/2IN(:1,:2,:3);

Rewrite of @xnor solution, kudos to him.

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

J, 6 bytes

+/e.+:

Try it with J.js.

How it works

+/e.+:    Monadic verb. Argument: A
    +:    Double the elements of A.
+/        Compute the sum of the elements of A.
  e.      Test for membership.
\$\endgroup\$
3
\$\begingroup\$

APL, 8 5 bytes

+/∊+⍨

This is a monadic function train that accepts an array and returns a boolean (0/1 in APL). It uses the same algorithm as xnor's Python 3 answer.

Explanation:

   +⍨  ⍝ Double the input (+⍨x is the same as x+x)
  ∊    ⍝ Test the membership of
+/     ⍝ The sum of the input

Try it online

Saved 3 bytes thanks to Dennis!

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

DUP, 31 chars / 39 bytes

[2ø2ø2ø++2/\%3ø^=3ø2ø=3ø3ø=||.]

Try it here!

My first DUP submission ever! Unicode is your oyster.

It's an anonymous function/lambda. Usage:

5 3 2[2ø2ø2ø++2/\%3ø^=3ø2ø=3ø3ø=||.]!

Explanation

[                               {start lambda}
 2ø2ø2ø                         {duplicate 3 inputnums}
       ++                       {push sum(3 popped stack items)}
         2/\%                   {push (popped stack item)/2}
             3ø^=3ø2ø=3ø3ø=     {for all 3 inputs, -1 if inputnum=sum/2; else 0}
                           ||   {check if any of the 3 resulting values are truthy}
                             .  {output top of stack (boolean value)}
                              ] {end lambda}
\$\endgroup\$
4
  • \$\begingroup\$ I don't think that's how an encoding works... \$\endgroup\$ Feb 7, 2016 at 23:19
  • \$\begingroup\$ ø has code point 248, so it is one byte if encoded as ISO 8859-1. \$\endgroup\$
    – Dennis
    Feb 7, 2016 at 23:25
  • 1
    \$\begingroup\$ ... which is fine as long as the interpreter can actually work with an ISO 8859-1 encoded source file. \$\endgroup\$ Feb 8, 2016 at 11:28
  • \$\begingroup\$ @MartinBüttner I don't think it's possible to test that. \$\endgroup\$ Feb 9, 2016 at 1:40
3
\$\begingroup\$

Java 7, 81

boolean d(int[]a){int s=0,t=1;for(int b:a)s+=b;for(int b:a)t*=2*b-s;return t==0;}
\$\endgroup\$
3
\$\begingroup\$

Perl 6, 20 19 bytes

I have two functions equal in byte count, so I'll put both. Appreciate whichever tickles your fancy.

{@_∋@_.sum div 2}
{@_∋+~(@_.sum/2)}

Usage: assign either one to a variable from which you can call it.
EDIT: Thanks @b2gills for the byte reduction

\$\endgroup\$
4
  • \$\begingroup\$ {@_∋@_.sum div 2} and {@_∋+~(@_.sum/2)} are both shorter \$\endgroup\$ Feb 8, 2016 at 22:00
  • \$\begingroup\$ Oh thanks, I always forget you can call sum as a dotty method \$\endgroup\$
    – Hotkeys
    Feb 8, 2016 at 22:10
  • \$\begingroup\$ What does do ? \$\endgroup\$ Feb 9, 2016 at 8:45
  • \$\begingroup\$ "∋" is the 'contains' infix operator, which says that the left contains the right. It's the sister to the "∈" 'element' op which say that the left is an element of the right. They're both set ops and perl 6 actually supports many others too! docs.perl6.org/language/… \$\endgroup\$
    – Hotkeys
    Feb 9, 2016 at 17:37
3
\$\begingroup\$

Java 8 (lambda function), 29 bytes

// Lambda Signature: (int, int, int) -> boolean

(a,b,c)->a+b==c|a+c==b|b+c==a

Java code golf solutions are usually only short when the program does not have to be a fully functional program. (*cough cough* class declaration, main method)

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

Pyth, 6 bytes

/Q/sQ2

Try it online!

Expects input as a list of integers. Outputs 0 if no number can be built by subtracting the other two and >0 if at least one can.

Explanation:

Same algorithm as the answer of @xnor

/Q/sQ2

   sQ     # Sum all elements in the list
  /  2    # Divide the sum by 2
/Q        # Count Occurences of above number in the list
\$\endgroup\$
2
\$\begingroup\$

Kona 16 chars

{((+/x)%2)_in x}

Takes a vector from the stack, sums them, divides by 2 and determines if it's in the vector. Returns 1 as truthy and 0 as falsey.

Called via

> {((+/x)%2)_in x} [(2;3;5)]
1
> {((+/x)%2)_in x} [(2;3;4)]
0
\$\endgroup\$
2
\$\begingroup\$

jq, 17 characters

(Yet another rewrite of xnor's Python 3 answer. Upvotes should go to that one.)

contains([add/2])

Input: array of 3 integers.

Sample run:

bash-4.3$ jq 'contains([add/2])' <<< '[5, 3, 2]'
true

bash-4.3$ jq 'contains([add/2])' <<< '[2, 3, -5]'
false

On-line test:

jq, 18 characters

(17 characters code + 1 character command line option.)

contains([add/2])

Input: list of 3 integers.

Sample run:

bash-4.3$ jq -s 'contains([add/2])' <<< '5 3 2'
true

bash-4.3$ jq -s 'contains([add/2])' <<< '2 3 -5'
false
\$\endgroup\$
2
\$\begingroup\$

MATL, 5 bytes

Using @xnor's great approach:

s2/Gm

Try it online!

s    % implicitly input array of three numbers. Compute their sum
2/   % divide by 2
G    % push input again
m    % ismember function: true if sum divided by 2 equals some element of the input

Brute-force approach, 12 bytes:

Y@TT-1h*!s~a

Try it online!

Y@       % input array of three numbers. Matrix with all
         % permutations, each one on a different row
TT-1h    % vector [1,1,-1]
*        % multiply with broadcast
!s       % transpose, sum of each column (former row)
~a       % true if any value is 0
\$\endgroup\$
2
\$\begingroup\$

𝔼𝕊𝕄𝕚𝕟, 7 chars / 9 bytes

ï⒮≔⨭ï/2

Try it here (Firefox only).

Meh. I'm still finding better ways. It's just @xnor's awesome algorithm.

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

CJam, 10 12 bytes

l~:d_:+2/&

2 bytes removed thanks to @MartinBüttner.

This displays a number as truthy result, and no output as falsy result.

Try it here

l~     e# read line and evaluate. Pushes the array
:d     e# convert array to double
_      e# duplicate
:+     e# fold addition on the array. Computes sum of the array
2/     e# divide sum by 2
&      e# setwise and (intersection)
\$\endgroup\$
0
2
\$\begingroup\$

Seriously, 6 bytes

,;䫡u

Outputs 0 if false and a positive integer otherwise.

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

Mathematica, 20 19 bytes

MemberQ[2{##},+##]&

Works similarly to most of the other answers.

\$\endgroup\$
1
  • \$\begingroup\$ How about MemberQ[2{##},+##]&? (and you forgot your byte count) \$\endgroup\$ Feb 7, 2016 at 20:26
2
\$\begingroup\$

Haskell, 20 bytes

(\l->sum l/2`elem`l)

Using xnor's solution.

\$\endgroup\$
5
  • \$\begingroup\$ Since (/) doesn't work for integers and the challenge asks for integers, I'm not sure that this is actually a valid solution. \$\endgroup\$
    – Zeta
    Feb 9, 2016 at 12:13
  • \$\begingroup\$ I did not see that. Should the type conversion be part of the code? Like this: (\l->sum l/2`elem`l).map fromInteger and it can be used like this: ((\l->sum l/2`elem`l).map fromInteger) ([2,3,5] :: [Integer]). I guess what threw me off was xnor mentioning the use of python 3 so the input didn't have to be 3.0 instead of 3. I thought the input type wasn't specified, just the way they were written... \$\endgroup\$ Feb 9, 2016 at 12:44
  • \$\begingroup\$ If the type is a really a problem shouldn't the fact that I'm taking a list as input be more of an issue? \$\endgroup\$ Feb 9, 2016 at 12:57
  • \$\begingroup\$ Good point. I would ask OP about that. But given that all the other answers also use a list, I guess it's OK (also, now I get why your function didn't type check when using tuples). \$\endgroup\$
    – Zeta
    Feb 9, 2016 at 13:06
  • \$\begingroup\$ Yes if the input was a tuple instead of a list neither sum nor elem would work, I should probably have specified it was a list but since this answer is literally what xnor submitted (in Haskell) I didn't think it was necessary. :) \$\endgroup\$ Feb 9, 2016 at 13:12
2
\$\begingroup\$

Perl, 24 + 4 = 28 bytes

$^+=$_/2 for@F;$_=$^~~@F

Requires -paX flags to run, prints 1 as True and nothing as False:

-X disables all warnings.

$ perl -paXe'$^+=$_/2 for@F;$_=$^~~@F' <<< '5 3 7'
$ perl -paXe'$^+=$_/2 for@F;$_=$^~~@F' <<< '5 3 8'
1
\$\endgroup\$
3
  • \$\begingroup\$ Inspiring one. Inspired this: $_=eval(y/ /+/r)/2~~@F (uses same command-line options). \$\endgroup\$
    – manatwork
    Feb 9, 2016 at 11:33
  • \$\begingroup\$ @manatwork Interesting way to use tr :) \$\endgroup\$ Feb 9, 2016 at 14:04
  • \$\begingroup\$ You could leave that -X out by specifying some Perl version [5.10 .. 5.18). (Smart match was introduced in 5.10 and experimental warnings were introduced in 5.18. Any version between those two will work fine with ~~ without -X.) \$\endgroup\$
    – manatwork
    Feb 9, 2016 at 16:41
2
\$\begingroup\$

R, 23 bytes

sum(x<-scan())%in%(2*x)

Try it online!

Shameless port of xnor's answer.

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

05AB1E, 4 bytes

DO;¢

Using 0 as falsy and > 0 as truthy. Uses CP-1252 encoding.

\$\endgroup\$
3
  • \$\begingroup\$ What's the "stupid" thing that makes this non-competing? \$\endgroup\$
    – Kyle Kanos
    Feb 7, 2016 at 13:34
  • \$\begingroup\$ @KyleKanos I already have written in Info.txt that ; halves the top of the stack. But guess what, I've never implemented it -_-. \$\endgroup\$
    – Adnan
    Feb 7, 2016 at 13:36
  • 1
    \$\begingroup\$ Ah. I can see how that'd do it \$\endgroup\$
    – Kyle Kanos
    Feb 7, 2016 at 13:37
2
\$\begingroup\$

Prolog (SWI), 35 bytes

\A:-permutation([X,Y,E],A),X-Y=:=E.

Try it online!

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

Jolf, 6 bytes

Try it here!

 hx½ux
_hx    the input array
   ½ux  has half the sum of the array

This is xnor's awesome solution to the problem, but in Jolf.

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

Pylons, 8

Yet another implementation of xnor's algorithm.

i:As2A/_

How it works:

i    # Get command line input.
:A   # Initialize a constant A.
  s  # Set A to the sum of the stack.
2    # Push 2 to the stack.
A    # Push A to the stack.
/    # Divide A/2
_    # Check if the top of the stack is in the previous elements.
     # Print the stack on quit.
\$\endgroup\$
1
\$\begingroup\$

SpecBAS - 36 bytes

Uses xnors formula

1 INPUT a,b,c: ?(a+b+c)/2 IN [a,b,c]

outputs 1 if true and 0 if false

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

05AB1E, 6 5 bytes

;Oм_O

-1 byte by creating a port of @xnor's Python 3 algorithm.

Try it online or verify all test cases.

Explanation:

·        # Halve every item in the input-array
         #  i.e. [10,6,4] → [5.0,3.0,2.0]
 O       # Sum this array
         #  i.e. [5.0,3.0,2.0] → 10.0
  м_O    # Output 1 if the input-array contain this sum, 0 otherwise
         #  i.e. [10,6,4] and 10.0 → 1

I'm pretty sure м_O can be shortened, but I'm not sure which command(s) I have to use for it..

\$\endgroup\$

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.