The handshake problem

The handshake problem is the classic problem that for n people in a room, if they all shake hands, what's the total number of handshakes that occur.

You code should take an input of any number and output the number of handshakes, both in base ten.

Also the code should not let non-integers through. You should output a falsey in this case. The only expected inputs are positive whole integers and positive real numbers - you don't need to worry about complex numbers or strings as inputs. This should mean that you should expect n >= 0

Test cases

(N:handshakes)
0:0
10:45
20:190
10.5:0
1337:893116


Normal golfing rules apply and shortest code wins. If your code isn't self explanatory, please explain.

Jelly and 05AB1E are the winners, both at 2 bytes

• What exactly can we expect in terms of "non-integer" inputs? (having said that, I feel like the error checking might amount to more than the actual challenge) Jun 14 '16 at 14:08
• Please have a look at our list of things to avoid when writing challenges. Bonuses are one of them. I would suggest removing it since it doesn't really add anything to the challenge. Oh, and also check out our sandbox. That's the place to get rid of some quirks in your challenge before you post it. Jun 14 '16 at 14:14
• So... does that mean -0, 10., 10.0 and .1? (I'm assuming you mean nonnegative - sorry for being a pendant, but stuff like this does tend to matter for esoteric languages which don't have an easy number eval function :P) Jun 14 '16 at 14:18
• I'm having a think about this challenge and was wondering - why does the challenge allow floats as input, out of curiosity? I'm not sure the error checking adds much to the challenge (and it also makes the challenge a lot harder and less nice for some languages) Jun 14 '16 at 14:40
• @george Yes, you should search for dupes. But if you have to start by explaining that you did, it's a good indicator that it's either 1) very trivial, or 2) so close to being a dupe you needed to justify it. Neither are promising. Jun 14 '16 at 16:33

JavaScript ES6, 16

n=>n%1?0:~-n*n/2


Test

f=n=>n%1?0:~-n*n/2

function test()
{
var i=I.value
O.textContent=f(i)
}  
<input id=I oninput=test()><span id=O></span>

• One of the shortest JavaScript answers I've seen :-) Jun 14 '16 at 16:44
• What's the advantage of this over n=>(n-1)*n/2? Jun 15 '16 at 9:47
• @Eterm the advantage of ~-n over (n-1) is 2 bytes less. The test of n%1 is required from the spec to detect non-integer input Jun 15 '16 at 9:50
• Thanks edc, this is why I'm a terrible golfer, I always miss half the requirements. Jun 15 '16 at 9:53

05AB1E, 2 bytes

Code:

2c

• Oh, so 05AB1E programs are just Jelly programs backwards? Jun 15 '16 at 3:38
• So that's how they're so short! Jun 15 '16 at 15:47

MATL, 3 bytes

2Xn


Try it online!

The code computes the binomial coefficient "n choose 2", where n is the input. For non-integer input no output is produced.

       % Take input implicitly
2      % Push 2
Xn     % n-choose-k
% Display implicitly

• This is a good way to crack it, I though that it was possible, but doubted any languages had a built in combination func Jun 14 '16 at 14:52
• @george I think that's what the Jelly and 05AB1E answers do too Jun 14 '16 at 14:54
• @Luis_Mendo Ah probably because they use c for combination rather than p which is permutation Jun 14 '16 at 14:55

Brainfuck, 22 21 bytes

,[-[->+>+<<]>[-<+>]<]


Try it online! Note, that brainfuck takes input and output through ASCII, so to enter a "49", you enter ascii value 49, e.g. 1. Brainfuck has no concept of non-integers, so it is impossible to enter one.

Jelly, 2 bytes

c2


Try it online!

• Note to others: Due to a bug in Jelly's source, this errored (and, therefore, produced the correct, empty output for non-integer arguments. This has been fixed, but the answer is valid in the penultimate revision of the Jelly interpreter. Jun 14 '16 at 17:06
• Is an empty output falsey? Jun 14 '16 at 17:26
• @DrGreen The empty string is falsy in Jelly, so I'd say it is. Jun 14 '16 at 20:36

Matlab, 61 23 bytes

@(x)~mod(x,1)*x*(x-1)/2


Improvements courtesy Luis Mendo.

@(x)eval('if isnumeric(x) disp((mod(x,1)==0)*x*(x-1)/2);end')

An anonymous function that calls eval. Matlab considers all numbers entered to be doubles unless you explicitly tell it otherwise, so testing for integerness via built-in isn't really an option unless you want to condition your input heavily-- thus the isnumeric and the mod1.

As well, Matlab doesn't allow conditional statements in anonymous functions, so you have to kludge around that by way of an eval statement that evaluates a string. So fun.

The "falsey" output is that it doesn't print anything at all for nonnumerics and prints 0 for a non-integer numeric. For a valid input, it will print the result.

• Why do you need isnumeric? The input is guaranteed to be numeric. Also, you can use ~ instead of ==0. And disp is not needed, because function output is allowed by defaut. So you could just use @(x)~mod(x,1)*x*(x-1)/2 Jun 15 '16 at 10:24
• Matlab errors on a non-numeric input to mod(), so I was coding to prevent that; I didn't realize that we'd only be expected to ever receive numeric inputs! Also I didn't realize I didn't have to disp(). Thanks! Jun 15 '16 at 13:08
• Welcome! And very good answer BTW. We need more Matlab answers here! :-) Jun 15 '16 at 13:46

Python, 37 50, 46, 32, 26 bytes

lambda a:a%1==0and a*~-a/2


Making use of the fact that the solution of the handshake problem is (N-1) + (N-2) ... 2 + 1 for N people. The most problematic is the falsey value when a non-int is given.

Big thanks to Leaky Nun and Martin Ender!

• Welcome to PPCG, and have fun here! Jun 14 '16 at 14:24
• @LeakyNun Thanks a lot for the improvements and the welcome! Jun 14 '16 at 14:26
• What does ~ mean. Is that Python 2 only? Jun 14 '16 at 14:32
• @george ~ is bitwise not, equivalent to -n-1. It's also in Python 3. Jun 14 '16 at 14:33

CJam, 7 bytes

ri_(*2/


Computes n*(n−1), where n is the input. For non-integer input it produces no output.

Try it online!

r     e# Read input
i     e# Convert to integer
_     e# Duplicate
(     e# Subtract 1
*     e# Multiply
2/    e# Divide by 2.
e# Implicit display


Mathematica, 19 bytes

#(#-1)/2/._Real->0&


This first computes the result using the explicit formula n(n-1)/2 but then replaces it with 0 if the that gives a floating-point result.

Just for fun, some alternatives to computing the result (minus the input validation) are:

#~Binomial~2
Tr@Range@#-#
n~Sum~{n,#-1}
PolygonalNumber@#-#


R, 28 bytes

Returns 0 if the input, x, is not an integer

x=scan();(x%%1==0)*x*(x-1)/2


ArnoldC, 266 bytes

ArnoldC has no concept of non-integers, so it is impossible to enter one.

LISTEN TO ME VERY CAREFULLY f
GIVE THESE PEOPLE AIR
HEY CHRISTMAS TREE r
YOU SET US UP 0
GET TO THE CHOPPER r
HERE IS MY INVITATION n
GET DOWN 1
YOU'RE FIRED n
ENOUGH TALK
I'LL BE BACK r
HASTA LA VISTA, BABY


Explanations:

DeclareMethod f
MethodArguments n
NonVoidMethod
DeclareInt r
SetInitialValue 0
AssignVariable r
SetValue n
MinusOperator 1
MultiplicationOperator n
DivisionOperator 2
EndAssignVariable
Return r
EndMethodDeclaration


CJam, 5 bytes

ri,1b


Prints nothing (except to STDERR) for non-integer input.

Try it online!

Explanation

ri  e# Read input and try to convert to integer N.
,   e# Turn into range [0 1 2 ... n-1].
1b  e# Sum the list by treating it as base-1 digits. We do this instead of
e# a simple reduction (:+) because the latter fails for empty lists.


Desmos, 11 bytes

.5nn-.5n
n=1


Try it here

Ungolfed formula:

• This does not seem to handle the non-integers case. Jun 16 '16 at 0:02
• @ Mama Fun Roll Do you expect for there to be partial people there? Jun 16 '16 at 14:21
• It is a test case that you have to handle. "Also the code should not let non-integers through. You should output a falsey in this case." Jun 16 '16 at 14:57
• That's why I have the variable slider set to integers. Jun 16 '16 at 15:53
• Oh, I was entering input through the text box. Nevermind, sorry :P Jun 16 '16 at 16:39

Hoon, 30 bytes

|=
n/@
(div (mul n (dec n)) 2)


Just compute (n * (n-1))/2. Hoon is strongly typed, so you can't call this function with a float or negative number.

Pyth, 7 bytes

?sIQ.cQ2Z
.x.cQ2Z


Test suite.

Python 3, 22 bytes

lambda z:sum(range(z))


Makes use of Python's standard library. Raises an error whenever the function is fed with a non-integer.

• Welcome to PPCG! Nice first post! Jun 15 '16 at 12:55

Python 3, 32 16 bytes

lambda n:n*~-n/2


Throws an error if n is not an integer.

Old Version:

lambda n:(0,n*~-n/2)[n==int(n)]

• Uou can use bitwise operators ~- to remove the brackets. Do n*~-n/2 Jun 23 '16 at 19:37
• Welcome to Programming Puzzles & Code Golf! Unfortunately, the spec requires the output to be falsy if the input is non-integral. Jun 23 '16 at 20:13

PowerShell v2+, 33 bytes

param($n)$n*($n-1)/2*($n-is[int])


Full program. 20 bytes to compute n(n-1)/2 and 13 bytes to validate input. Uses the -is operator, so requires V2 or newer.

Dyalog APL, 9 bytes

2∘!×(|=⌊)


The chose-2 times (whether the abs equals the floor).

J, 14 8 bytes

2&!*]=<.


6 bytes saved thanks to miles!

Explaination:

2&!      NB. Binomial coefficient of 2 and the argument
*     NB. Times...
]=<. NB. argument == floor(argument)


Previous solution: -:@(*<:)*(=<.)

• You can use ! to calculate the binomial coefficient. Then you can shorten it to 2&!*]=<. for 8 bytes. Jun 14 '16 at 16:21

dc, 18 bytes

[d/]sqdX0!=qd1-*2/


Explanation

[d/]sq


Store in register q a macro that replaces top of stack with 1 (by dividing by itself).

dX0!=q


If there are any fraction digits, then execute the macro.

d1-*2/


Compute ½n(n-1). If we started with 1 (either as input or because a non-integer value was entered) the result will be 0.

Factor with load-all, 12 bytes

[ iota sum ]


Java, 363 bytes

I thought I ought to make sure everybody gets a chance to meet everybody else.

Unfortunately some of the party guests do have to ask if they've met someone before, to avoid shaking someone's hand twice. Hopefully the guests are pretty good at recognizing faces.

Golfed:

import java.util.ArrayList;public class H{static int h = 0;public static void main(String[] a){int b = Integer.parseInt(a[0]);P[] e = new P[b];for(int i=0;i<b;i++){e[i] = new P();}for(P p : e){for(P o : e){p.s(o);}}System.out.print(h);}}class P {ArrayList<P> l = new ArrayList<P>();void s(P o){if(o.equals(this)){return;}if(!o.l.contains(this)){H.h++;l.add(o);}}}


Un-golfed:

import java.util.ArrayList;

public class PartyHost {
static int shakes = 0;
public static void main(String[] args){
int amount = Integer.parseInt(args[0]);
Person[] people = new Person[amount];
for(int i=0; i<amount;i++){
people[i] = new Person();
// welcome to the party!
}
// well, we gotta get this party rockin'. hey, have you met my friend...
for(Person p : people){
for(Person other : people){
p.handshake(other);
}
}
System.out.print(shakes);
}
}

class Person {
void handshake(Person other){
// hmm, have we met already?
if(other.equals(this)){
// I mean, I guess I could shake hands with myself... maybe later.
return;
}
// it seems not!
// *firm grasp. maintain eye contact*
// uh oh don't hold on too long
// hope he doesn't grab too early or too late
PartyHost.shakes++;
}
}
}


𝔼𝕊𝕄𝕚𝕟, 5 chars / 7 bytes

МƦ⁽ï2


Try it here (ES6 browsers only).

Builtins are pretty cool.

RETURN, 8 bytes

[$1-×2÷]  Try it here. Anonymous lambda that leaves result as top of stack. Usage: 10[$1-×2÷]!


Explanation

[      ]  lambda
$1- n-1 × *n 2÷ /2  Google Sheets, 17 14 bytes =((B1^2)-B1)/2  Cell B1 is the input. Haskell, 15 bytes f x=sum[1..x-1]  [x..y] ranges are inclusive... Oh and I don't know how to handle the non-integers... Golisp, 18 bytes {(n)~[+range[1n]]}  Python equivalent: lambda n: sum(range(1, n)). Oh and Golisp don't have floating point number (for now) Perl 5, 25 bytes A subroutine: {($_=pop)*!/\D/*($_-1)/2}  See it in action: perl -e'print sub{($_=pop)*!/\D/*(\$_-1)/2}->(3.14)'

• \. would work as well as \D. Jun 15 '16 at 22:15