Sum all Sub Array in Linux

Consider Array (1 2 3) , Below are the Sub-Array for this Array and their sum.
(1): Sum of this sub-array is 1
(2): Sum of this sub-array is 2
(3): Sum of this sub-array is 3
(1 2): Sum of this sub-array is 3
(2 3): Sum of this sub-array is 5
(1 2 3): Sum of this sub-array is 6
So, there are 6 Sub Array in this Particular Array.
Now, we need to find out sum of all these Array using shell scripting.
NOTE : You can remove the outer most while loop and just pass the value of k where k is the length of Sub Array in order to find Sum of Sub Array having length N(which is K here in our case).

arr=(1 2 3) ## Array of 3 elements
len1=${#arr[@]} ## Length of Array arr
SumSubArr=()## created Empty Array
LenOfSubArr=1 ## Minimum length of Sub Array is 1.
while [ $LenOfSubArr -le $len1 ]
do
k=$LenOfSubArr
j=0
i=0
k1=$(( $k - 1))
k2=$k
loopLen=$(($len1 - $k2 + 1))
while [ $i -lt $loopLen ] ## This will run for all Sub Array of Particular Length using Variable LenOfSubArr.
do
sum_arr=0
while [ $j -lt $k ] ## This loop will sum values of all elements present in each Sub Array
do
sum_arr=$(($sum_arr + ${arr[j]}))
j=$(( $j + 1))
done
SumSubArr+=$sum_arr
i=$(( $i + 1))
j=$(( $j - $k1))
k=$(( $k + 1))
done
LenOfSubArr=$(( $LenOfSubArr +1))
done
echo ${SumSubArr[*]}


Related posts