All Sub Array having sum=0

In this blog, first we need to understand sub array definition and code to find sum of all Sub-Array in an Array. For that, please refer to this blog. Now, we need to find all Sub-Array whose Sum is equal to zero. Consider an array (1 -1 2 1 -3) and there are three sub-array whose sum is zero mentioned below.
( 1 -1)
(2 1 -3)
(1 -1 2 1 -3)

Below is the Shell Script which will give all sub-array whose sum is 0 .

arr=(1 -1 2 1 -3) ## Array of 3 elements
len1=${#arr[@]} ## Length of Array arr
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
NewArray=()## creating blank array for outer loop which will run for sub-array of particular length
index=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]}))
NewArray+=(${arr[j]}) ## Appending elements in sub array NewArray
j=$(( $j + 1))
index=$(( $index + 1))
done
if [ $sum_arr -eq "0" ] ##checking sum ==0
then
echo "Sub Array having sum=0 is "${NewArray[@]} ##printing Sub array having sum=0
fi
i=$(( $i + 1))
j=$(( $j - $k1))
k=$(( $k + 1))
done
LenOfSubArr=$(( $LenOfSubArr +1))
done


Related posts