forked from manwar/perlweeklychallenge-club
-
Notifications
You must be signed in to change notification settings - Fork 1
/
ch-2.lua
49 lines (42 loc) · 1 KB
/
ch-2.lua
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
46
47
48
49
#!/opt/local/bin/lua
--
-- See ../README.md
--
--
-- Run as: lua ch-2.lua -s SIZE < input-file
--
--
-- Parse option, and exit if incorrect
--
local size = -1
if #arg == 2 and arg [1] == "-s"
then size = arg [2] + 0
end
if size < 0
then io . stderr : write ("Requires a '-s SIZE' option\n")
os . exit (1)
end
--
-- Iterate over the input, line by line.
-- For each line, count the number of 0's on each position of the sections
-- Calculate the number of 1's. Add the minimum of the two to a running sum.
--
for line in io . lines () do
local sections = #line / size
local sum = 0
for i = 0, size - 1 do
local zeros = 0
for j = 0, sections - 1 do
index = j * size + i + 1
if string . sub (line, index, index) == "0"
then zeros = zeros + 1
end
end
local ones = sections - zeros
if zeros < ones
then sum = sum + zeros
else sum = sum + ones
end
end
io . write (sum, "\n")
end