配列の与えられた要素の断片を合計します。

配列の与えられた要素の断片を合計します。

さて、ここに私のコードがあります。おそらく私がやろうとしていることのポイントを知ることができます。私は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

このスクリプトを使った私の目標:

  • 乱数を含む配列の最初の20桁の合計を取得してエコーします。

  • 乱数を含む配列の最後の20桁の合計を取得してエコーします。

  • 最初の合計が2番目の合計より大きいかどうかを確認します。

どんな助けでもいいでしょう!スラムしてください。

ベストアンサー1

合計関数から始めましょう。私たちは実際にこれをもう少し一般化したいと思います。同様の操作を実行するいくつかのループから外れるように、すべてのパラメータを追加してくださいreduce 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; }

残りは簡単です。

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

おすすめ記事