The handshake problem

3

2

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

george

Posted 2016-06-14T13:58:42.833

Reputation: 1 495

4What 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) – Sp3000 – 2016-06-14T14:08:30.703

Related. – Martin Ender – 2016-06-14T14:10:18.063

@Sp3000 I have edited the question now. You'll only expect real and whole numbers – george – 2016-06-14T14:10:30.797

1What about negative numbers? – Leaky Nun – 2016-06-14T14:11:41.993

@MartinEnder indeed it is, but the differ eve is that the handshake problem is slightly more real world – george – 2016-06-14T14:12:27.290

Might ask for some specifics if that's okay - which of the following might we expect as input?: -0, -1, 10., 10.0, .1, -.1, -10., -10.0 – Sp3000 – 2016-06-14T14:13:04.163

7

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.

– Denker – 2016-06-14T14:14:17.177

@Sp3000 expect all the positive values – george – 2016-06-14T14:16:22.323

2So... 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) – Sp3000 – 2016-06-14T14:18:59.070

If normal golfing rules apply, is there any reason you're excluding full programs?

– AdmBorkBork – 2016-06-14T14:21:14.620

@Sp3000 no thank you for asking. This is my first question so it's good to know how accurate I need to be in question defining. I wouldn't count -0 as some language would need to evaluate this first. So all numbers greater than 0. – george – 2016-06-14T14:22:36.797

Is erroring on invalid inputs allowed? – Leaky Nun – 2016-06-14T14:26:35.093

@TimmyD sorry didn't actually realise that was a set rule – george – 2016-06-14T14:28:53.053

@george Er... that's fine, welcome! Bit confused now though, since you said "greater than 0" in the comments but wrote "expect n>=0" – Sp3000 – 2016-06-14T14:29:38.347

@LeakyNun if you mean that it will give an error when an invalid n in entered no. – george – 2016-06-14T14:29:46.583

@Sp3000 whoops, yes greater than or equal to is correct. As in the test case 0 – george – 2016-06-14T14:30:54.267

7I'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) – Sp3000 – 2016-06-14T14:40:45.310

Also, Welcome to Programming Puzzles and Code Golf! I recommend posting future challenges to the Sandbox where they can get meaningful feedback before being posted to the main site. Enjoy your stay!

– AdmBorkBork – 2016-06-14T14:41:33.240

@TimmyD thanks! I will do in future – george – 2016-06-14T14:42:08.990

@Sp3000 when I coded the question myself, it was just n*(n-1)/2 which could take any value, but in the context of the question, there will only be a whole positive number of people in the room, so although it is computable for a float number, it is not contextual – george – 2016-06-14T14:44:15.637

1"I've searched for this question and couldn't find it" is often a strong hint that the question is really boring. – Peter Taylor – 2016-06-14T15:49:11.693

1@PeterTaylor so the game is over? No more new questions except for boring ones? – edc65 – 2016-06-14T16:16:15.680

1@edc65, the subtext that you read should not be "Don't search to see whether your question is a dupe" but "If you think it necessary to justify posting the question, think twice about posting it. Then if you're still planning to post it, think a third time." – Peter Taylor – 2016-06-14T16:22:26.383

1@PeterTaylor Aren't you suppose to check that a question has not been asked before? If one does not and it is a dupe, it was a waste of a post. Correct me if I'm wrong but that's is how I thought is worked here? – george – 2016-06-14T16:27:47.417

4@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. – Geobits – 2016-06-14T16:33:53.740

@Geobits okay that's interesting. I'll keep it in mind – george – 2016-06-14T16:37:41.580

@DrGreenEggsandIronMan sorry I should have removed that after TimmyD's comment. It can be a full program, or just a function, unnamed or names. In PPCG any style of answer is accepted – george – 2016-06-14T20:28:15.570

This would be massively better if invalid input did not need to be considered. Arbitrarily overriding the defaults is a bad idea.

– Mego – 2016-06-16T00:16:47.040

@Mego see my previous reply about the context of the question – george – 2016-06-16T00:18:24.607

Answers

5

Jelly, 2 bytes

c2

Try it online!

Doorknob

Posted 2016-06-14T13:58:42.833

Reputation: 68 138

1Note 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. – Dennis – 2016-06-14T17:06:51.173

1Is an empty output falsey? – James – 2016-06-14T17:26:04.577

2@DrGreen The empty string is falsy in Jelly, so I'd say it is. – Dennis – 2016-06-14T20:36:01.307

9

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>

edc65

Posted 2016-06-14T13:58:42.833

Reputation: 31 086

One of the shortest JavaScript answers I've seen :-) – Luis Mendo – 2016-06-14T16:44:15.317

What's the advantage of this over n=>(n-1)*n/2? – Eterm – 2016-06-15T09:47:10.957

@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 – edc65 – 2016-06-15T09:50:34.797

Thanks edc, this is why I'm a terrible golfer, I always miss half the requirements. – Eterm – 2016-06-15T09:53:30.050

8

05AB1E, 2 bytes

Code:

2c

Try it online!.

Adnan

Posted 2016-06-14T13:58:42.833

Reputation: 41 965

10Oh, so 05AB1E programs are just Jelly programs backwards? – MCMastery – 2016-06-15T03:38:07.297

1So that's how they're so short! – James – 2016-06-15T15:47:32.843

6

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

Luis Mendo

Posted 2016-06-14T13:58:42.833

Reputation: 87 464

This is a good way to crack it, I though that it was possible, but doubted any languages had a built in combination func – george – 2016-06-14T14:52:07.897

@george I think that's what the Jelly and 05AB1E answers do too – Luis Mendo – 2016-06-14T14:54:07.223

@Luis_Mendo Ah probably because they use c for combination rather than p which is permutation – george – 2016-06-14T14:55:48.617

6

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.

James

Posted 2016-06-14T13:58:42.833

Reputation: 54 537

5

Matlab, 61 23 bytes

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

Improvements courtesy Luis Mendo.

Old answer:

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

sintax

Posted 2016-06-14T13:58:42.833

Reputation: 291

1

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

– Luis Mendo – 2016-06-15T10:24:24.040

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! – sintax – 2016-06-15T13:08:49.650

Welcome! And very good answer BTW. We need more Matlab answers here! :-) – Luis Mendo – 2016-06-15T13:46:46.877

4

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!

Mathias711

Posted 2016-06-14T13:58:42.833

Reputation: 141

Welcome to PPCG, and have fun here! – Leaky Nun – 2016-06-14T14:24:14.597

@LeakyNun Thanks a lot for the improvements and the welcome! – Mathias711 – 2016-06-14T14:26:39.583

What does ~ mean. Is that Python 2 only? – george – 2016-06-14T14:32:20.290

@george ~ is bitwise not, equivalent to -n-1. It's also in Python 3. – Sp3000 – 2016-06-14T14:33:52.367

3

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

Luis Mendo

Posted 2016-06-14T13:58:42.833

Reputation: 87 464

3

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@#-#

Martin Ender

Posted 2016-06-14T13:58:42.833

Reputation: 184 808

3

R, 28 bytes

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

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

bouncyball

Posted 2016-06-14T13:58:42.833

Reputation: 401

3

ArnoldC, 266 bytes

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

LISTEN TO ME VERY CAREFULLY f
I NEED YOUR CLOTHES YOUR BOOTS AND YOUR MOTORCYCLE n
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
HE HAD TO SPLIT 2
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

Zycho

Posted 2016-06-14T13:58:42.833

Reputation: 441

2

Pyth, 7 bytes

?sIQ.cQ2Z
.x.cQ2Z

Test suite.

Leaky Nun

Posted 2016-06-14T13:58:42.833

Reputation: 45 011

1Erroring with nothing on stdout is considered falsy. – isaacg – 2016-06-17T04:29:33.150

@isaacg You know, the OP said "if you mean that it will give an error when an invalid n in entered no."

– Leaky Nun – 2016-06-17T04:31:00.643

2

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.

Martin Ender

Posted 2016-06-14T13:58:42.833

Reputation: 184 808

2

Desmos, 11 bytes

.5nn-.5n
n=1

Try it here

Ungolfed formula:
(n(n-1))/2

weatherman115

Posted 2016-06-14T13:58:42.833

Reputation: 605

This does not seem to handle the non-integers case. – Mama Fun Roll – 2016-06-16T00:02:39.637

@ Mama Fun Roll Do you expect for there to be partial people there? – weatherman115 – 2016-06-16T14:21:51.230

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." – Mama Fun Roll – 2016-06-16T14:57:51.493

That's why I have the variable slider set to integers. – weatherman115 – 2016-06-16T15:53:59.620

Oh, I was entering input through the text box. Nevermind, sorry :P – Mama Fun Roll – 2016-06-16T16:39:36.253

Yeah, you can always increase the upper limit – weatherman115 – 2016-06-16T17:56:46.757

2

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.

RenderSettings

Posted 2016-06-14T13:58:42.833

Reputation: 620

2

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.

Filippo Costa

Posted 2016-06-14T13:58:42.833

Reputation: 121

1Welcome to PPCG! Nice first post! – Rɪᴋᴇʀ – 2016-06-15T12:55:03.913

2

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)]

B Person

Posted 2016-06-14T13:58:42.833

Reputation: 21

1Uou can use bitwise operators ~- to remove the brackets. Do n*~-n/2 – george – 2016-06-23T19:37:40.717

1Welcome to Programming Puzzles & Code Golf! Unfortunately, the spec requires the output to be falsy if the input is non-integral. – Dennis – 2016-06-23T20:13:53.450

1

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.

AdmBorkBork

Posted 2016-06-14T13:58:42.833

Reputation: 41 581

1

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: -:@(*<:)*(=<.)

Loovjo

Posted 2016-06-14T13:58:42.833

Reputation: 7 357

You can use ! to calculate the binomial coefficient. Then you can shorten it to 2&!*]=<. for 8 bytes. – miles – 2016-06-14T16:21:18.520

1

Dyalog APL, 9 bytes

2∘!×(|=⌊)

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

Adám

Posted 2016-06-14T13:58:42.833

Reputation: 37 779

1

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.

Toby Speight

Posted 2016-06-14T13:58:42.833

Reputation: 5 058

1

Factor with load-all, 12 bytes

[ iota sum ]

Same as this answer.

cat

Posted 2016-06-14T13:58:42.833

Reputation: 4 989

1

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 {
    ArrayList<Person> already_shook = new ArrayList<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;
        }
        if(!other.already_shook.contains(this)){
            // 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++;
            already_shook.add(other);
        }
    }
}

nasonfish

Posted 2016-06-14T13:58:42.833

Reputation: 163

0

Perl 5, 25 bytes

A subroutine:

{($_=pop)*!/\D/*($_-1)/2}

See it in action:

perl -e'print sub{($_=pop)*!/\D/*($_-1)/2}->(3.14)'

msh210

Posted 2016-06-14T13:58:42.833

Reputation: 3 094

\. would work as well as \D. – msh210 – 2016-06-15T22:15:23.667

0

, 5 chars / 7 bytes

МƦ⁽ï2

Try it here (ES6 browsers only).

Builtins are pretty cool.

Mama Fun Roll

Posted 2016-06-14T13:58:42.833

Reputation: 7 234

0

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

Mama Fun Roll

Posted 2016-06-14T13:58:42.833

Reputation: 7 234

0

Google Sheets, 17 14 bytes

=((B1^2)-B1)/2

Cell B1 is the input.

weatherman115

Posted 2016-06-14T13:58:42.833

Reputation: 605

0

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

TuxCrafting

Posted 2016-06-14T13:58:42.833

Reputation: 4 547

0

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)

TuxCrafting

Posted 2016-06-14T13:58:42.833

Reputation: 4 547