3
\$\begingroup\$

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

\$\endgroup\$
  • 4
    \$\begingroup\$ 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) \$\endgroup\$ – Sp3000 Jun 14 '16 at 14:08
  • 7
    \$\begingroup\$ 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. \$\endgroup\$ – Denker Jun 14 '16 at 14:14
  • 2
    \$\begingroup\$ 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) \$\endgroup\$ – Sp3000 Jun 14 '16 at 14:18
  • 7
    \$\begingroup\$ 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) \$\endgroup\$ – Sp3000 Jun 14 '16 at 14:40
  • 4
    \$\begingroup\$ @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. \$\endgroup\$ – Geobits Jun 14 '16 at 16:33

29 Answers 29

5
\$\begingroup\$

Jelly, 2 bytes

c2

Try it online!

\$\endgroup\$
  • 1
    \$\begingroup\$ 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. \$\endgroup\$ – Dennis Jun 14 '16 at 17:06
  • 1
    \$\begingroup\$ Is an empty output falsey? \$\endgroup\$ – DJMcMayhem Jun 14 '16 at 17:26
  • 2
    \$\begingroup\$ @DrGreen The empty string is falsy in Jelly, so I'd say it is. \$\endgroup\$ – Dennis Jun 14 '16 at 20:36
9
\$\begingroup\$

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>

\$\endgroup\$
  • \$\begingroup\$ One of the shortest JavaScript answers I've seen :-) \$\endgroup\$ – Luis Mendo Jun 14 '16 at 16:44
  • \$\begingroup\$ What's the advantage of this over n=>(n-1)*n/2? \$\endgroup\$ – Eterm Jun 15 '16 at 9:47
  • \$\begingroup\$ @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 \$\endgroup\$ – edc65 Jun 15 '16 at 9:50
  • \$\begingroup\$ Thanks edc, this is why I'm a terrible golfer, I always miss half the requirements. \$\endgroup\$ – Eterm Jun 15 '16 at 9:53
8
\$\begingroup\$

05AB1E, 2 bytes

Code:

2c

Try it online!.

\$\endgroup\$
  • 10
    \$\begingroup\$ Oh, so 05AB1E programs are just Jelly programs backwards? \$\endgroup\$ – MCMastery Jun 15 '16 at 3:38
  • 1
    \$\begingroup\$ So that's how they're so short! \$\endgroup\$ – DJMcMayhem Jun 15 '16 at 15:47
6
\$\begingroup\$

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
\$\endgroup\$
  • \$\begingroup\$ This is a good way to crack it, I though that it was possible, but doubted any languages had a built in combination func \$\endgroup\$ – george Jun 14 '16 at 14:52
  • \$\begingroup\$ @george I think that's what the Jelly and 05AB1E answers do too \$\endgroup\$ – Luis Mendo Jun 14 '16 at 14:54
  • \$\begingroup\$ @Luis_Mendo Ah probably because they use c for combination rather than p which is permutation \$\endgroup\$ – george Jun 14 '16 at 14:55
6
\$\begingroup\$

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.

\$\endgroup\$
5
\$\begingroup\$

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.

\$\endgroup\$
  • 1
    \$\begingroup\$ 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 \$\endgroup\$ – Luis Mendo Jun 15 '16 at 10:24
  • \$\begingroup\$ 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! \$\endgroup\$ – sintax Jun 15 '16 at 13:08
  • \$\begingroup\$ Welcome! And very good answer BTW. We need more Matlab answers here! :-) \$\endgroup\$ – Luis Mendo Jun 15 '16 at 13:46
4
\$\begingroup\$

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!

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

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
\$\endgroup\$
3
\$\begingroup\$

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@#-#
\$\endgroup\$
3
\$\begingroup\$

R, 28 bytes

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

x=scan();(x%%1==0)*x*(x-1)/2
\$\endgroup\$
3
\$\begingroup\$

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
\$\endgroup\$
2
\$\begingroup\$

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.
\$\endgroup\$
2
\$\begingroup\$

Desmos, 11 bytes

.5nn-.5n
n=1

Try it here

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

\$\endgroup\$
  • \$\begingroup\$ This does not seem to handle the non-integers case. \$\endgroup\$ – Mama Fun Roll Jun 16 '16 at 0:02
  • \$\begingroup\$ @ Mama Fun Roll Do you expect for there to be partial people there? \$\endgroup\$ – weatherman115 Jun 16 '16 at 14:21
  • \$\begingroup\$ 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." \$\endgroup\$ – Mama Fun Roll Jun 16 '16 at 14:57
  • \$\begingroup\$ That's why I have the variable slider set to integers. \$\endgroup\$ – weatherman115 Jun 16 '16 at 15:53
  • \$\begingroup\$ Oh, I was entering input through the text box. Nevermind, sorry :P \$\endgroup\$ – Mama Fun Roll Jun 16 '16 at 16:39
2
\$\begingroup\$

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.

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

Pyth, 7 bytes

?sIQ.cQ2Z
.x.cQ2Z

Test suite.

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

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.

\$\endgroup\$
  • 1
    \$\begingroup\$ Welcome to PPCG! Nice first post! \$\endgroup\$ – Rɪᴋᴇʀ Jun 15 '16 at 12:55
2
\$\begingroup\$

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)]
\$\endgroup\$
  • 1
    \$\begingroup\$ Uou can use bitwise operators ~- to remove the brackets. Do n*~-n/2 \$\endgroup\$ – george Jun 23 '16 at 19:37
  • 1
    \$\begingroup\$ Welcome to Programming Puzzles & Code Golf! Unfortunately, the spec requires the output to be falsy if the input is non-integral. \$\endgroup\$ – Dennis Jun 23 '16 at 20:13
1
\$\begingroup\$

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.

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

Dyalog APL, 9 bytes

2∘!×(|=⌊)

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

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

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

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

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.

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

Factor with load-all, 12 bytes

[ iota sum ]

Same as this answer.

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

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);
        }
    }
}
\$\endgroup\$
0
\$\begingroup\$

𝔼𝕊𝕄𝕚𝕟, 5 chars / 7 bytes

МƦ⁽ï2

Try it here (ES6 browsers only).

Builtins are pretty cool.

\$\endgroup\$
0
\$\begingroup\$

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
\$\endgroup\$
0
\$\begingroup\$

Google Sheets, 17 14 bytes

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

Cell B1 is the input.

\$\endgroup\$
0
\$\begingroup\$

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

\$\endgroup\$
0
\$\begingroup\$

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)

\$\endgroup\$
0
\$\begingroup\$

Perl 5, 25 bytes

A subroutine:

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

See it in action:

perl -e'print sub{($_=pop)*!/\D/*($_-1)/2}->(3.14)'
\$\endgroup\$
  • \$\begingroup\$ \. would work as well as \D. \$\endgroup\$ – msh210 Jun 15 '16 at 22:15

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.