Hey guys, I’m new to bash scripting/coding and don’t know how to shorten execution time in my code. I’m going through everything I can in the beginner category writing in python 3.6, then powershell, then bash. I got it to work on the first two, but I don’t know enough BASH to simplify my code. Here it is for INTEST:
read n k
ans=0
for i in $(seq 1 $n); do
read x
a=$(( x % k ))
if [ "$a" = "0" ]; then
ans=$(($ans+1))
fi
done
echo $ans
Any help or suggestions would be greatly appreciated.
The only BASH answers that see to be fast enough, are those that let awk do all the work.
I tried changing you code to use readarray -n $n ar to read all lines at once to an array and then iterate over each element.
ans=0
read n k
readarray -n $n ar
i=0
for x in "${ar[@]}"
#while [ $i -le $n ]
do
a=$(( x % k ))
if [ "$a" = "0" ]; then
ans=$(( ans+1 ))
fi
#i=$(( i+1 ))
done
echo $ans
Reading in the lines is fast enough, but the iteration itself is the slow part. BASH seems to be way to slow to iterate 10^7 times. On my local computer, the code takes 8.4s split like
real
0m8,465s
user
0m8,288s
sys
0m0,176s
You code gives
real
0m12,204s
user
0m10,846s
sys
0m1,372s
which is way slower in reading the data. But reading in the data, is not the problem.