diff options
| author | Alex Pickering <alex@cogarr.net> | 2025-02-07 12:49:48 -0600 |
|---|---|---|
| committer | Alex Pickering <alex@cogarr.net> | 2025-02-07 12:49:48 -0600 |
| commit | 3555be54c2abb8d5ece008a60dbdfbde0ffbddd7 (patch) | |
| tree | 278876284d07118ecdea5c48cb6453f3122887f0 /25/1.lua | |
| download | advent_of_code_2022-master.tar.gz advent_of_code_2022-master.tar.bz2 advent_of_code_2022-master.zip | |
Diffstat (limited to '25/1.lua')
| -rw-r--r-- | 25/1.lua | 74 |
1 files changed, 74 insertions, 0 deletions
diff --git a/25/1.lua b/25/1.lua new file mode 100644 index 0000000..53d8794 --- /dev/null +++ b/25/1.lua @@ -0,0 +1,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]] |
