Suma un segmento dado de elementos en una matriz (bash)

De acuerdo, aquí está mi código. Probablemente entiendas lo que estoy tratando de hacer. No soy tan bueno con Linux bash.

#random numbers MAXCOUNT=100 count=1 while [ "$count" -le $MAXCOUNT ]; do number[$count]=$RANDOM let "count += 1" done #adding function function sum() { echo $(($1+$2)) } #main section first="${count[1-20]}" echo "The sum of the first 20 elements are: $first" last="${count[1-20]}" echo "The sum of the last 20 elements is: $last" if [ $first -gt $last ]; then echo "The sum of the first 20 numbers is greater." else echo "The sum of the last 20 numbers is greater." fi 

Mis objectives con este guion:

  • Obtenga y repita la sum de los primeros 20 numbers de la matriz que contiene numbers de randoms.

  • Obtenga y repita la sum de los ÚLTIMOS 20 numbers de la matriz que contiene numbers de randoms.

  • Eche si la primera sum es mayor que la segunda sum.

¡Cualquier ayuda sería genial! Bash, por favor.

Comencemos con la function sum. En realidad, queremos que sea un poco más generalizado: haga que sume TODOS los arguments para poder deshacernos de un par de loops haciendo algo así como networkinguce func array .

 # Since you are using bash, let's use declare to make things easier. # Don't use those evil `function foo` or `function foo()` stuffs -- obsolete bourne thing. sum(){ declare -i acc; for i; do acc+=i; done; echo $acc; } 

El rest es bastante fácil.

 MAXCOUNT=100 num=() # Let's use the less evil native 0-based indices. for ((i=0; i<MAXCOUNT; i++)); do nums+=($RANDOM); done # https://gnu.org/software/bash/manual/bashref.html#Shell-Parameter-Expansion # set f to the sum of the 20 elements of nums starting from elem 0 f=$(sum "${nums[@]:0:20}"); echo f20=$f # set l to the sum of the LAST 20 elems of nums, mind the space l=$(sum "${nums[@]: -20}"); echo l20=$l if ((f > l)); then echo f20g; else echo l20g; fi 

Otra posible solución:

 #!/bin/bash max=100 rng=20 ### Problem conditions texta="The sum of the %.3sst %d elements is: %d\n" ### Output textb="The first sum is %ser than the last sum\n" ### Output unset num ### used vars for (( s1=s2=c=0 ; c<max ; c++ )) do num[c]=$RANDOM (( c<rng )) && (( s1+=num[c] )) ### first sum. (( c>=max-rng )) && (( s2+=num[c] )) ### last sum. done compare=small; (( s1 > s2 )) && compare=bigg printf "$texta" "first" "$rng" "$s1" printf "$texta" " last" "$rng" "$s2" printf "$textb" "$compare" 

 The sum of the first 20 elements is: 348899 The sum of the last 20 elements is: 336364 The first sum is bigger than the last sum 
 unset num[@] sum; c=-1 while num[c+=1]=$RANDOM do case $c in ([2-7]?) ;; ($((sum+=num[c])):|99) ! eval ' printf "$@$sum" "$'"$((sum<$3?2:4))\" greater";; (19) set "The sum of the %-5s 20 elements is:\t%s\n" \ first "$sum" last ""; sum=0 esac||break done 

 The sum of the first 20 elements is: 308347 The sum of the last 20 elements is: 306596 The sum of the first 20 elements is: greater