Register
It is currently Fri Dec 19, 2014 5:49 pm

average and max number.


All times are UTC - 6 hours


Post new topic Reply to topic  [ 3 posts ] 
Author Message
 PostPosted: Fri Dec 24, 2010 12:28 pm   

Joined: Fri Dec 24, 2010 12:20 pm
Posts: 2
Hi!

I have a problem. How to get the average and max number from array (in my case), which we enter through the input values!!

printnumbers()
{
echo ${ARRAY[*]}
}

sortnumbers()
{
for((i=1;i<count;i++))
do
Temp=${ARRAY[i]}
j=$((i-1))
while [ $Temp -lt ${ARRAY[j]} ]
do
ARRAY[j+1]=${ARRAY[j]}
let j--
if [ $j == -1 ]
then
break
fi
done
ARRAY[j+1]=$Temp
done
}

echo "Input number for sorting"
read -a ARRAY
count=${#ARRAY[@]}



echo "Number before sorting:"
printnumbers
sortnumbers

echo "Sorted number: "
printnumbers


Top
 Profile  
 PostPosted: Fri Dec 24, 2010 2:18 pm   
User avatar

Joined: Sun Jun 27, 2010 12:57 am
Posts: 192
my suggestion:
Code:
#!/bin/bash

function printnumbers { echo ${ARRAY[*]}; }
function sortnumbers { ARRAY=( $(for i in ${ARRAY[@]}; do echo "$i"; done | sort -n) ); }

function average { echo "${ARRAY[@]}" | awk '{ for (i=1; i<=$NF; i++) total+=$i; } END { printf("%.2f\n", total/$NF); }'; }
function average2 { for i in ${ARRAY[@]}; do ((total+=$i)); done; echo $((total/${#ARRAY[@]})); }

function maximum { echo "${ARRAY[@]}" | awk '{ for (i=1; i<=$NF; i++) max=($i>max)?$i:max; } END { printf("%d\n", max); }'; }
function maximum2 { max=0; for i in ${ARRAY[@]}; do [ $i -gt $max ] && max=$i; done; echo "$max"; }

echo "Input number for sorting"
read -a ARRAY

echo "Number before sorting:"
printnumbers
sortnumbers

echo "Sorted number: "
printnumbers
echo "Average: $(average) or $(average2)"
echo "Maximum: $(maximum) or $(maximum2)"


Top
 Profile  
 PostPosted: Sat Dec 25, 2010 3:57 am   

Joined: Fri Dec 24, 2010 12:20 pm
Posts: 2
Thanks for help Patsie.


Top
 Profile  
Display posts from previous:  Sort by  
Post new topic Reply to topic  [ 3 posts ] 

All times are UTC - 6 hours


Who is online

Users browsing this forum: Bing [Bot] and 1 guest


You cannot post new topics in this forum
You cannot reply to topics in this forum
You cannot edit your posts in this forum
You cannot delete your posts in this forum
You cannot post attachments in this forum

Jump to:  


BashScripts | Promote Your Page Too
Powered by phpBB © 2011 phpBB Group
© 2003 - 2011 USA LINUX USERS GROUP