배열의 주어진 요소 조각을 합산합니다(bash).

배열의 주어진 요소 조각을 합산합니다(bash).

좋아, 여기 내 코드가 있습니다. 아마도 내가 하려는 일의 요점을 알 수 있을 것입니다. 저는 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개 숫자의 합계를 가져오고 에코합니다.

  • 첫 번째 합계가 두 번째 합계보다 큰지 여부를 확인합니다.

어떤 도움이라도 좋을 것입니다! 슬램해 주세요.

답변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

답변2

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

답변3

또 다른 가능한 해결책:

#!/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

관련 정보