Bash Coding Exercise – HandShake


At the annual meeting of Board of Directors of Acme Inc, every one starts shaking hands with everyone else in the room. Given the fact that any two persons shake hand exactly once, Can you tell the total count of handshakes?

Input Format
The first line contains the number of test cases T, T lines follow.
Each line then contains an integer N, the total number of Board of Directors of Acme.

Output Format

Print the number of handshakes for each test-case in a new line.

Constraints

1 <= T <= 1000 0 < N < 106 Sample Input 2 1 2 Sample Output 0 1 Explanation Case 1 : The lonely board member shakes no hands, hence 0. Case 2 : There are 2 board members, 1 handshake takes place.

The formula is just tex_0c6a43afe707710e7b62f0041e89e700 Bash Coding Exercise - HandShake bash script hacker rank linux linux shell math which is the combination number to choose any two from the number n.

It can be computed as tex_16702b8ade76da62d5a7bcde062b8a80 Bash Coding Exercise - HandShake bash script hacker rank linux linux shell math .

1
2
3
4
5
6
7
8
9
#!/bin/bash
 
read n
i=0
while [ $i -lt $n ]; do
    read x
    echo $((x*(x-1)/2))
    i=$((i+1))
done
#!/bin/bash

read n
i=0
while [ $i -lt $n ]; do
    read x
    echo $((x*(x-1)/2))
    i=$((i+1))
done

You can also use other for-syntaxs, such as :

1
2
3
4
5
6
7
8
#!/bin/bash
 
read n
for i in $(seq 1 $n)
do
    read x
    echo $((x*(x-1)/2))
done
#!/bin/bash

read n
for i in $(seq 1 $n)
do
    read x
    echo $((x*(x-1)/2))
done

or the C-style,

1
2
3
4
5
6
7
8
#!/bin/bash
 
read n
for (( i=0; i<$n; i ++ ))
do
    read x
    echo $((x*(x-1)/2))
done
#!/bin/bash

read n
for (( i=0; i<$n; i ++ ))
do
    read x
    echo $((x*(x-1)/2))
done

The BASH script is a real programming language, therefore you can see the support of BASH in many puzzle-solving online judges.

bash-shellshock Bash Coding Exercise - HandShake bash script hacker rank linux linux shell math

bash-shellshock

–EOF (The Ultimate Computing & Technology Blog) —

GD Star Rating
loading...
404 words
Last Post: Using FluentAssertions Library to Write Better Unit Tests in .NET C#
Next Post: How to Valid IPv6 Addresses using BASH and Regex ?

The Permanent URL is: Bash Coding Exercise – HandShake

Leave a Reply