Difference of three input integers

30

5

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.

Mir

Posted 2016-02-07T09:35:52.753

Reputation: 403

5This 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. – xnor – 2016-02-07T09:37:26.143

Hey I fixed it a little. Hope this suffices! – Mir – 2016-02-07T09:45:26.737

2

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.

– xnor – 2016-02-07T09:48:15.623

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? – Sp3000 – 2016-02-07T10:03:27.580

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! – Mir – 2016-02-07T10:18:58.117

Hmm k... just another question sorry - does input have to be True and False exactly or is any kind of truthy/falsy output allowed?

– Sp3000 – 2016-02-07T10:21:19.007

(note that not all languages have a concept of True or False, or might have different names for them) – Sp3000 – 2016-02-07T10:28:51.837

This looks familiar, but I can't find the one I'm thinking of. I think it might've been in Code Review SE, so not a golfing challenge. I'm also pretty sure I've seen it given as a job interview question more than once, though they probably wouldn't appreciate you giving them any of the answers below in response... – Darrel Hoffman – 2016-02-07T21:21:06.297

@Geobits Well I screwed that up – Angzuril – 2016-02-07T23:16:44.407

It is a classic homework question in introductory programming classes so you may have seen it there. @Sp3000 Anything Truthy or Falsy in the output might make this a little too easy. I leave it up to those with more experience to decide – Mir – 2016-02-07T23:30:51.503

Answers

14

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!

Adnan

Posted 2016-02-07T09:35:52.753

Reputation: 41 965

51

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.

xnor

Posted 2016-02-07T09:35:52.753

Reputation: 115 687

7

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.

Neil

Posted 2016-02-07T09:35:52.753

Reputation: 95 035

You can save two bytes by replacing || with | (I think) – HyperNeutrino – 2016-02-09T03:16:05.983

@AlexL. Ah right I was too hung up on having to return Booleans. – Neil – 2016-02-09T08:59:00.203

Even with booleans, | returns a boolean if and only if both values are booleans. So true | false == true, but 3 | 5 == 7. The same applies && and &. The only difference between | and || when it comes to booleans: | will take the first value and the second value and find the OR of those two. || will take the first value; if it is true, return true, otherwise, return the second value. – HyperNeutrino – 2016-02-09T13:50:27.877

@AlexL. true | false evaluates to 1 in JavaScript (which is truthy, but not Boolean). – Neil – 2016-02-09T18:52:13.000

Oh. Sorry, I don't really use JS. I mostly use Java, which is where I got that information from. ;) – HyperNeutrino – 2016-02-09T19:01:20.367

4

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!

Alex A.

Posted 2016-02-07T09:35:52.753

Reputation: 23 761

4

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)

Conor O'Brien

Posted 2016-02-07T09:35:52.753

Reputation: 36 228

Try x=>x.some(a=>a==eval(x.join\+`)/2)`, which saves 4 bytes. – Mama Fun Roll – 2016-02-07T23:29:17.690

@ӍѲꝆΛҐӍΛПҒЦꝆ Thanks! Nice trick. – Conor O'Brien – 2016-02-07T23:34:16.023

x=>x.some(a=>2*a==x[0]+x[1]+x[2]) seems to work. – jrich – 2016-02-09T02:42:24.817

@jrich Thanks! Nice trick! – Conor O'Brien – 2016-02-09T02:44:53.767

3

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.

Jeto

Posted 2016-02-07T09:35:52.753

Reputation: 1 601

3

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

Hotkeys

Posted 2016-02-07T09:35:52.753

Reputation: 1 015

{@_∋@_.sum div 2} and {@_∋+~(@_.sum/2)} are both shorter – Brad Gilbert b2gills – 2016-02-08T22:00:44.837

Oh thanks, I always forget you can call sum as a dotty method – Hotkeys – 2016-02-08T22:10:51.160

What does do ? – User112638726 – 2016-02-09T08:45:27.763

"∋" 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! http://docs.perl6.org/language/unicode_texas#Other_acceptable_codepoints

– Hotkeys – 2016-02-09T17:37:06.643

3

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.

Dennis

Posted 2016-02-07T09:35:52.753

Reputation: 196 637

3

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}

Mama Fun Roll

Posted 2016-02-07T09:35:52.753

Reputation: 7 234

I don't think that's how an encoding works... – Conor O'Brien – 2016-02-07T23:19:42.767

ø has code point 248, so it is one byte if encoded as ISO 8859-1. – Dennis – 2016-02-07T23:25:51.073

1... which is fine as long as the interpreter can actually work with an ISO 8859-1 encoded source file. – Martin Ender – 2016-02-08T11:28:49.167

@MartinBüttner I don't think it's possible to test that. – Mama Fun Roll – 2016-02-09T01:40:39.810

3

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;}

Marky Markov

Posted 2016-02-07T09:35:52.753

Reputation: 141

3

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)

HyperNeutrino

Posted 2016-02-07T09:35:52.753

Reputation: 26 575

2

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

Denker

Posted 2016-02-07T09:35:52.753

Reputation: 6 639

2

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

andlrc

Posted 2016-02-07T09:35:52.753

Reputation: 1 613

Inspiring one. Inspired this: $_=eval(y/ /+/r)/2~~@F (uses same command-line options). – manatwork – 2016-02-09T11:33:04.200

@manatwork Interesting way to use tr :) – andlrc – 2016-02-09T14:04:04.127

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.) – manatwork – 2016-02-09T16:41:56.730

2

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

Luis Mendo

Posted 2016-02-07T09:35:52.753

Reputation: 87 464

2

05AB1E, non-competing

4 bytes, non-competing because of a stupid thing. Code:

DO;¢

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

Adnan

Posted 2016-02-07T09:35:52.753

Reputation: 41 965

What's the "stupid" thing that makes this non-competing? – Kyle Kanos – 2016-02-07T13:34:39.840

@KyleKanos I already have written in Info.txt that ; halves the top of the stack. But guess what, I've never implemented it -_-.

– Adnan – 2016-02-07T13:36:11.337

1Ah. I can see how that'd do it – Kyle Kanos – 2016-02-07T13:37:10.053

2

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

Kyle Kanos

Posted 2016-02-07T09:35:52.753

Reputation: 4 270

2

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)

Luis Mendo

Posted 2016-02-07T09:35:52.753

Reputation: 87 464

2

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

manatwork

Posted 2016-02-07T09:35:52.753

Reputation: 17 865

2

, 7 chars / 9 bytes

ï⒮≔⨭ï/2

Try it here (Firefox only).

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

Mama Fun Roll

Posted 2016-02-07T09:35:52.753

Reputation: 7 234

2

Seriously, 6 bytes

,;䫡u

Outputs 0 if false and a positive integer otherwise.

Mego

Posted 2016-02-07T09:35:52.753

Reputation: 32 998

2

Mathematica, 20 19 bytes

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

Works similarly to most of the other answers.

LegionMammal978

Posted 2016-02-07T09:35:52.753

Reputation: 15 731

How about MemberQ[2{##},+##]&? (and you forgot your byte count) – Martin Ender – 2016-02-07T20:26:43.410

2

Haskell, 20 bytes

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

Using xnor's solution.

basile-henry

Posted 2016-02-07T09:35:52.753

Reputation: 381

Since (/) doesn't work for integers and the challenge asks for integers, I'm not sure that this is actually a valid solution. – Zeta – 2016-02-09T12:13:37.427

I did not see that. Should the type conversion be part of the code? Like this: (\l->sum l/2\elem`l).map fromIntegerand 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... – basile-henry – 2016-02-09T12:44:14.317

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? – basile-henry – 2016-02-09T12:57:36.413

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). – Zeta – 2016-02-09T13:06:22.477

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. :) – basile-henry – 2016-02-09T13:12:00.873

1

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..

Kevin Cruijssen

Posted 2016-02-07T09:35:52.753

Reputation: 67 575

1

R, 23 bytes

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

Try it online!

Shameless port of xnor's answer.

JayCe

Posted 2016-02-07T09:35:52.753

Reputation: 2 655

1

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.

Conor O'Brien

Posted 2016-02-07T09:35:52.753

Reputation: 36 228

1

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.

Morgan Thrapp

Posted 2016-02-07T09:35:52.753

Reputation: 3 574

1

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

Brian

Posted 2016-02-07T09:35:52.753

Reputation: 1 209