ogs
ogs

Reputation: 1239

Bash determine the difference between the highest and lowest variables

As part of three variables I would like to determine is the difference between the highest and the lowest is less than a defined range.

Val1
Val2    
Val3

Until now, I got only two Val and I used something like :

let diff=${Val1}-${Val2}

Then, I calculate the absolute value of contains into "diff".

if [ "$diff" -ge 0 ]                    
then                                
    absval=$diff                        
else                                
    let "absval = (( 0 - $diff ))"      
fi  

But now, what is the more efficient way to perfom this stuff ?

Upvotes: 0

Views: 315

Answers (4)

chepner
chepner

Reputation: 531838

The most efficient way (which, you must realize, may not be the fastest way for any particular input) is to iterate though the list and simply keep track of the smallest and largest number so far.

while read num; do
    if (( num > highest )); then highest=num; fi
    if (( num < lowest )); then lowest=num; fi
done <<EOF
Val1
Val2    
Val3
...
EOF

diff=$(( highest - lowest ))

In theory, sorting is not the most efficient way to find the highest and lowest, since you don't need to do the extra work to put all the numbers in order. (In practice, you may need a very large number of numbers before the O(n) algorithm in bash outperforms the O(n lg n) algorithm implemented by sort in C.)

Upvotes: 2

user4453924
user4453924

Reputation:

Using awk if that is allowed

awk '{max=$1<max&&max~/./?max:$1;min=$1>min&&min~/./?min:$1}END{print max-min}' file

Input

1
2
10
5
3
9

Output

9

Upvotes: 2

rahul
rahul

Reputation: 304

If you can put them in a file, you can do it in a single command sort -V <filename>. This sorts them numerically . If you have lots of values to sort, this might be a better option with much less code.

Here is an example:

cat <filename>
1
2
10
5
3
9

sort -n <filename>
1
2
3
5
9
10

If you'd like to get the lowest and the highest numbers and the difference between them , you can do so like this.

result=$(sort -n <filename>)
high=$(echo "$result" | tail -1)
low=$(echo "$result" | head -1)
diff=`expr $high - $low`

echo "Highest is $high"
echo "Lowest is $low"
echo "Diff is $diff"

Upvotes: 0

Barmar
Barmar

Reputation: 781751

Use if tests to compare the variables directly.

if [[ $Val1 -gt $Val2 ]]
then highest=$Val1
else highest=$Val2
fi

if [[ $Val3 -gt $highest ]]
then highest=$Val3
fi

If you have more variables, you can just keep doing this:

if [[ $Val4 -gt $highest ]]
then highest=$Val4
fi

Use similar steps with -lt to get the lowest value.

Another way to do it is to sort the values and then get the first and last lines of this:

sorted=$(printf "%s\n" $Var1 $Var2 $Var3 | sort -n)
highest=$(echo "$sorted" | tail -1)
lowest=$(echo "$sorted" | head -1)
diff=$(( highest - lowest ))

Upvotes: 2

Related Questions