We use cookies to ensure you have the best browsing experience on our website. Please read our cookie policy for more information about how we use cookies.
- Prepare
- Mathematics
- Fundamentals
- Handshake
- Discussions
Handshake
Handshake
Sort by
recency
|
331 Discussions
|
Please Login in order to post a comment
Uses the combination formula: n(n - 1) / 2 Formula explanation: think of ‘n’ as the number of people, ‘-1’ is used in (n - 1) to restrict people from shaking their own hand. Dividing by 2 to remove all duplicates (will explain further below). n contains all the people and they can all shake a total of (n - 1) hands, hence n * (n - 1).
For instance, if n = 5, we want the unique handshakes of 5 people.
Counting all the shakes from the 1st, 2nd, 3rd, 4th, 5th. We get the following combinations from n * (n - 1): 1-2, 1-3, 1-4, 1-5 2-1, 2-3, 2-4, 2-5 3-1, 3-2, 3-4, 3-5 4-1, 4-2, 4-3, 4-5 5-1, 5-2, 5-3, 5-4
Notice how we have 5 rows (number of people) and 4 columns (number of handshakes each person can do). Since we cannot have 1-1, 2-2, 3-3, 4-4, 5-5; we do not have a 5th column.
[1-2, 1-3, 1-4, 1-5] 2-1, [2-3, 2-4, 2-5] 3-1, 3-2, [3-4, 3-5] 4-1, 4-2, 4-3, [4-5] 5-1, 5-2, 5-3, 5-4
The []pairs are the unique combinations, which happen to be half the total data set, which is why we divide by 2, to remove duplicates.
if(n == 2) { return 1; } else if (n <= 1 ) { return 0; }
return (n**2 - n)//2
Swift Solution:
guys how solve