三个输入整数的差


30

实现一个函数diff,将三个整数x,y和z作为输入。它应该返回是否从另一个中减去这些数字中的一个得出第三个数字。

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

您不必命名该函数,您可以实现默认的输入方法,以上示例不是严格的准则。


5
这是一个合理的挑战,但是没有必要将其限制为Python或函数。通常,这种限制是不受欢迎的,因为它们限制了参与。另外,您应该包括一些测试用例。
xnor

嘿,我修好了一点。希望这足够了!
米尔

2
看起来更好!我仍然强烈建议允许使用默认的输入法,尤其是程序,因为某些语言没有功能。并且,允许函数使用其他名称或不使用名称。
xnor

现在第一段和最后一段是冲突的,所以要仔细检查-我们必须编写一个函数还是完整的程序好吗?
Sp3000 '16

完整的程序很好,除了遵循默认的输入法之外,我想施加尽可能小的限制。ef python3的例子很简洁!
米尔

Answers:


14

果冻5 3字节

感谢@ Sp3000节省了两个字节!

代码使用与@xnor的最佳答案完全相同的算法:

SfḤ

说明:

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

[]既是虚假的,又是真理。

在线尝试!


51

Python 3,21个字节

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

如果两个数字相加,则三个数字的总和将是另一个数字的两倍,因此,总和的一半将成为列表的元素。除非数字指定为3.0而不是,否则需要Python 3来避免地板分割3


7

ES6,31个字节

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

如果需要命名函数,请添加5个字节 diff

编辑:由于@Alex L,节省了2个字节。


您可以通过替换|||(我认为)来节省两个字节
HyperNeutrino

@AlexL。嗯,对,我太挂了,不得不返回布尔值。
尼尔

即使具有布尔值,|当且仅当两个值均为布尔值时,才返回布尔值。所以true | false == true,但是3 | 5 == 7。这同样适用于&&&。布尔值之间|||布尔值之间的唯一区别是:|将取第一个值和第二个值并找到这两个值的OR||将取第一个值;如果为true,则返回true,否则返回第二个值。
HyperNeutrino'2

@AlexL。true | false在JavaScript中的计算结果为1(这是正确的,但不是布尔值)。
尼尔

哦。抱歉,我不是真的使用JS。我主要使用Java,这是我从中获取信息的地方。;)
HyperNeutrino

4

APL,8个 5字节

+/∊+⍨

这是一个单子函数序列,它接受一个数组并返回一个布尔值(在APL中为0/1)。它使用与xnor的Python 3 Answer相同的算法。

说明:

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

在线尝试

感谢Dennis,节省了3个字节!


4

的JavaScript ES6,38个 34 33字节

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

非常简单的匿名函数,它借鉴了Python的答案。将输入x作为数组;返回truefalse。字节被剃成Molarmanful和jrich

一个38字节的程序,将每个数字作为参数:

(a,b,c)=>[a,b,c].some(t=>t==(a+b+c)/2)

试试看x=>x.some(a=>a==eval(x.join`+`)/2),节省4个字节。
Mama Fun Roll

@ӍѲꝆΛҐӍΛПҒЦꝆ谢谢!好招
科纳·奥布莱恩

x=>x.some(a=>2*a==x[0]+x[1]+x[2])似乎有效。
jrich 2016年

@jrich谢谢!好招!
Conor O'Brien

3

Oracle SQL 11.2,49字节

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

重写@xnor解决方案,对他表示敬意。


3

J,6个字节

+/e.+:

J.js一起尝试

怎么运行的

+/e.+:    Monadic verb. Argument: A
    +:    Double the elements of A.
+/        Compute the sum of the elements of A.
  e.      Test for membership.

3

DUP,31个字符/ 39个字节

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

Try it here!

我第一次提交DUP! Unicode是您的牡蛎。

这是一个匿名函数/ lambda。用法:

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

说明

[                               {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}

我不认为编码是这样工作的……
Conor O'Brien

ø具有代码点248,因此如果编码为ISO 8859-1,则为1个字节。
丹尼斯

1
......这是很好的,只要解释实际上可以工作与ISO 8859-1编码的源文件。
马丁·恩德

@MartinBüttner我认为无法测试。
Mama Fun Roll


3

Perl 6中,20 19个字节

我有两个字节数相等的函数,因此我将两者都放。欣赏让您心动的人。

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

用法:将其中一个分配给您可以从中调用的变量。
编辑:感谢@ b2gills的字节减少


{@_∋@_.sum div 2}而且{@_∋+~(@_.sum/2)}都较短
Brad Gilbert b2gills '16

噢,谢谢,我总是忘记您可以将sum称为点方法
Hotkeys

怎么办?
User112638726 '02

“∋”是“包含”中缀运算符,表示左侧包含右侧。它是“ε”“ element” op的姐妹,它说左边是右边的元素。他们都设置了操作,而perl 6实际上也支持许多其他功能!docs.perl6.org/language/...
热键

3

Java 8(lambda函数),29字节

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

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

Java代码高尔夫解决方案通常仅在程序不必是功能齐全的程序时才简短。(*咳嗽*类的声明,主要方法)


2

Pyth,6个字节

/Q/sQ2

在线尝试!

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

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.


What's the "stupid" thing that makes this non-competing?
Kyle Kanos

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

1
Ah. I can see how that'd do it
Kyle Kanos

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

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

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


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)

2

Seriously, 6 bytes

,;䫡u

Outputs 0 if false and a positive integer otherwise.


2

Mathematica, 20 19 bytes

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

Works similarly to most of the other answers.


How about MemberQ[2{##},+##]&? (and you forgot your byte count)
Martin Ender

2

Haskell, 20 bytes

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

Using xnor's solution.


Since (/) doesn't work for integers and the challenge asks for integers, I'm not sure that this is actually a valid solution.
Zeta

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

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

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

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

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

Inspiring one. Inspired this: $_=eval(y/ /+/r)/2~~@F (uses same command-line options).
manatwork

@manatwork Interesting way to use tr :)
andlrc

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

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.


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.

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


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


By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.