blob: 4ea37b5911d9455b50e44d3d21d7a5e43882bf13 (
plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
|
#!/bin/sh
#
# See ../README.md
#
#
# Run as: bash ch-2.sh -s SIZE < input-file
#
#
# Disable pathname expansion
#
set -f
#
# Read the option
#
while getopts "s:" name
do if [ "$name" = "s" ]
then size=$OPTARG
fi
done
#
# Iterate over the input. For each position, count the number of 0s,
# and calculate the number of 1s. Sum the minimum of those numbers.
#
while read line
do sections=$((${#line} / $size))
sum=0
for ((i = 0; i < size; i ++))
do zeros=0
for ((j = 0; j < sections; j ++))
do index=$(($j * $size + $i))
if [ "${line:$index:1}" == "0" ]
then zeros=$(($zeros + 1))
fi
done
ones=$(($sections - $zeros))
sum=$(($sum + ($zeros < $ones ? $zeros : $ones) ))
done
echo $sum
done
|