user3443599
user3443599

Reputation: 25

Compare Numbers not working properly (Bash Script in Hacker Rank)

According to the problem stated in the below link:

https://www.hackerrank.com/contests/bash-and-linux-shell-practice/challenges/bash-tutorials---comparing-numbers/problem

My code is working fine in Mac OSX terminal, but while submitting the same code in Hackerrank one of the test case is failing. I am not sure why this is happening. Would really appreciate any answers.

 read X
 read Y

 if [[ $X > $Y ]]
 then 
   echo "X is greater than Y"
 elif [[ $X < $Y ]]
 then
   echo "X is less than Y"
 else
   echo "X is equal to Y"
 fi

 HackerRank Custom Test Case:

 Compilation Successful
 Input (stdin)
 -100
 100
 Your Output
 X is greater than Y

Upvotes: 1

Views: 936

Answers (2)

dawg
dawg

Reputation: 104024

You can use the Bash double-parenthesis context ((...)) vs test context [[ ... ]] to get more typical arithmetic comparisons:

x=-5
y=5

if ((x>y)); then 
    echo "X is greater than Y"
elif ((x<y)); then
    echo "X is less than Y"
else
    echo "X is equal to Y"
fi

Or use an integer comparison inside [[ ... ]] test:

if [[ "$x" -gt "$y" ]]; then
    echo "X is greater than Y"
elif [[ "$x" -lt "$y" ]]; then
    echo "X is less than Y"
else
    echo "X is equal to Y"
fi

Inside [[ ... ]] the <,> or == tests string comparisons.

Both of these methods only work with integers; to use floats, you need to use awk, bc or other float interpreter. Be sure to use double quotes "$x" in the [[ test ]] and the quotes and sigil are not required for (( ))

With user input, be sure to test that $x and $y are actual numbers. Good tests here...

Upvotes: 4

Gordon Davisson
Gordon Davisson

Reputation: 125918

I'm not sure why you're getting that result; I get "X is less than Y" in actual bash. However, your script is actually wrong in a different way: in [[ ]], < and > do alphabetic comparison rather than numeric comparison. To understand the difference, consider that [[ 5 < 1000 ]] will come out as false, because "5" comes after "1" in character sorting order. To do numeric comparison, use -lt and -gt instead.

Upvotes: 3

Related Questions