small_potato
small_potato

Reputation: 1

Finding out the type of a triangle in Bash

I have this block of code to determine whether a triangle is Isosceles, Scalene or Equilateral after reading three inputs, X , Y and Z. Its constraints are:

  1. It should be between 1 and 1000
  2. The sum of any two sides should be greater than the third

It works well except for specific numbers such as 5 and 6 in which it doesn't output anything.

read X
read Y
read Z

if [[ $X -lt 1000 && $Y -lt 1000 && $Z -lt 1000 ]]
then 
    if [[ $X -gt 1 && $Y -gt 1 && $Z -gt 1 ]]
    then
        if [[ $((X + Y)) > $Z  &&  $((X + Z)) > $Y  &&  $((Y + Z)) > $X ]]
        then
            if [[ $X == $Y  &&  $X == $Z && $Y == $Z ]]
            then
                echo EQUILATERAL
            elif [[ $X == $Y && $X == $Z ]] || [[ $Y == $Z || $Y == $X ]] || [[ $Z == $Y || $Z == $X ]]
            then 
                echo ISOSCELES
            else
                echo SCALENE
            fi
        fi
    fi

fi

Please explain why it's not working as expected

Upvotes: 0

Views: 841

Answers (1)

tshiono
tshiono

Reputation: 22012

As @jhnc comments, > within [[ .. ]] operator is for string comparison. If you input 5's for x, y, and z, the comparison test will look like:

if [[ 10 > 5 ]] ...

which returns false as a result of string comparison. Please use arithmetic evaluation (( .. )) instead.

Then how about:

read x
read y
read z

# As a first step, eliminate error cases to simplify the logic
if (( x >= 1000 || y >= 1000 || z >= 1000 || x == 0 || y == 0 || z == 0)); then
    echo "out of range"
    exit
fi

if (( x + y <= z || y + z <= x || z + x <= y )); then
    echo "not a triangle"
    exit
fi

if (( x == y && y == z )); then
    echo "equilateral"
elif (( x == y || y == z || z == x )); then
    echo "isosceles"
else
    echo "scalene"
fi

Upvotes: 1

Related Questions