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
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
|
require "ext"
local snafu = {
["0"] = 0,
["1"] = 1,
["2"] = 2,
["-"] = -1,
["="] = -2,
}
local snafu_rev = {}
for k,v in pairs(snafu) do
snafu_rev[v] = k
end
local function decode(s)
local t = {}
for c in s:gmatch("(.)") do
table.insert(t,c)
end
local cursor = 1
local n = 0
while #t > 0 do
local val = table.remove(t)
n = n + (snafu[val] * cursor)
cursor = cursor * 5
end
return n
end
-- 4 8 9 0
local function encode(n,location)
--print("Encoding",n)
if snafu_rev[n] then
--print("Snafu of",n,"is",snafu_rev[n])
return snafu_rev[n]
end
local rem = n % 5
if rem == 0 or rem == 1 or rem == 2 then
return encode(math.floor(n/5)) .. snafu_rev[rem]
elseif rem == 3 or rem == 4 then
return encode(math.floor(n/5)+1) .. snafu_rev[rem - 5]
end
end
local sum = 0
for line in io.lines() do
sum = sum + decode(line)
end
print(encode(sum))
--[[
print(encode(6))
local encodings = {
[1]="1",
[2]="2",
[3]="1=",
[4]="1-",
[5]="10",
[6]="11",
[7]="12",
[8]="2=",
[9]="2-",
[10]="20",
[15]="1=0",
[20]="1-0",
[2022]="1=11-2",
[12345]="1-0---0",
[314159265]="1121-1110-1=0",
}
for k,v in pairs(encodings) do
local fe = encode(k)
print("Finished encoding of",k,"is",fe)
assert(fe == v)
end]]
|