declare -r TRUE=0 declare -r FALSE=1 declare -r MAX_POLY=5 declare -r MAX_COEF=10 declare poly_A_coefs=() declare poly_B_coefs=() declare poly_C_coefs=() # # void init() # function init() { local i=0 while [ $i -lt $MAX_POLY ] do poly_A_coefs[$i]=0 poly_B_coefs[$i]=0 poly_C_coefs[$i]=0 let i=$i+1 done return 0 } # # int is_num(const char *str) # function is_num() { local num=$1 local len=${#num} local i=0 local c while [ $i -lt $len ] do c=${num:$i:1} [ -n "${c/[0-9]/}" ] && return $FALSE let i=$i+1 done return $TRUE } # # int get_num(int min, int max) # function get_num() { local min=$1 local max=$2 local num read num is_num $num || return $FALSE [ ${num} -lt ${min} -o ${num} -gt ${max} ] && return $FALSE echo $num return $TRUE } # # int inputPolyNum(void) # function inputPolyNum() { local num=-1 while [ true ] do echo -n "Number of $1: " num=$(get_num 1 $MAX_POLY) [ $? -eq $TRUE ] && break echo "Out of range(1~$MAX_POLY). Retry!" done return $num } # # put random number into random position of array # function makeRandomPoly() { local poly=$1 local nr=$2 local pos local coef local sign local tmp local count=0 while (($count < $nr)) do let pos=$RANDOM%$MAX_POLY tmp="$poly[$pos]" [ ${!tmp} -ne 0 ] && continue let coef=($RANDOM%$MAX_COEF)+1 let sign=$RANDOM%2 [ $sign -eq 1 ] && eval $tmp=$coef || eval $tmp="-${coef}" ((count++)) done } # # add each paired entries for 2 arrays # function add_poly { local poly1=$1 local poly2=$2 local res=$3 local tmp1 local tmp2 local tmpr local pos local i=0 while (($i < $MAX_POLY)) do pos=$i ((i++)) tmp1=$poly1[$pos] tmp2=$poly2[$pos] tmpr=$res[$pos] eval let ${tmpr}=${!tmp1}+${!tmp2} done } # # print out each entries except 0 # function printPoly() { local poly=$1 local tmp local pos local exp local i=0 while (($i < $MAX_POLY)) do pos=$i ((i++)) tmp=$poly[$pos] [ ${!tmp} -eq 0 ] && continue let exp=$MAX_POLY-$pos-1 printf "%3dX^%-2d " "${!tmp}" "$exp" done echo "" } init inputPolyNum "A" declare -r poly_nr_A=$? inputPolyNum "B" declare -r poly_nr_B=$? makeRandomPoly poly_A_coefs $poly_nr_A makeRandomPoly poly_B_coefs $poly_nr_B add_poly poly_A_coefs poly_B_coefs poly_C_coefs echo -n "A : " printPoly poly_A_coefs echo -n "B : " printPoly poly_B_coefs echo -n "C=(A+B): " printPoly poly_C_coefs