From b76699fca6d799ccba8fd7848c0f90b97f7f8891 Mon Sep 17 00:00:00 2001 From: Logan G Date: Sat, 3 Dec 2022 00:45:41 -0700 Subject: [PATCH] Cleaned up Day 3 --- day3/day3.lua | 23 +++++++++-------------- day3/day3part2.lua | 29 ++++++++++++++--------------- 2 files changed, 23 insertions(+), 29 deletions(-) diff --git a/day3/day3.lua b/day3/day3.lua index 0d3d316..779ec5b 100644 --- a/day3/day3.lua +++ b/day3/day3.lua @@ -3,30 +3,25 @@ io.input(file) score = 0 -for line in file:lines() do - local first = string.sub(line, 1, #line/2) - local second = string.sub(line, #line/2 + 1, #line) - print(#first) - print(#second) +function find_duplicates(first, second) for i = 1, #first do local char = string.sub(first, i, i) if string.match(second, char) then - print(char) if char == string.upper(char) then - --print(string.byte(char) - string.byte("A") + 27) - score = score + string.byte(char) - string.byte("A") + 27 - goto continue + return string.byte(char) - string.byte("A") + 27 elseif char == string.lower(char) then - --print(string.byte(char) - string.byte("a")) - score = score + string.byte(char) - string.byte("a") + 1 - goto continue + return string.byte(char) - string.byte("a") + 1 end end - end +end - ::continue:: +for line in file:lines() do + local first = string.sub(line, 1, #line/2) + local second = string.sub(line, #line/2 + 1, #line) + + score = score + find_duplicates(first, second) end print(score) diff --git a/day3/day3part2.lua b/day3/day3part2.lua index de83ba1..af7c405 100644 --- a/day3/day3part2.lua +++ b/day3/day3part2.lua @@ -8,26 +8,25 @@ for line in file:lines() do table.insert(data, line) end +function find_duplicates(one, two, three) + for i = 1, #one do + local char = string.sub(one, i, i) + if string.match(two, char) and string.match(three, char) then + if char == string.upper(char) then + return string.byte(char) - string.byte("A") + 27 + elseif char == string.lower(char) then + return string.byte(char) - string.byte("a") + 1 + end + end + end +end + for i = 1, #data/3 do local one = data[(i-1)*3+1] local two = data[(i-1)*3+2] local three = data[(i-1)*3+3] - for n = 1, #one do - local char = string.sub(one, n, n) - if string.match(two, char) and string.match(three, char) then - if char == string.upper(char) then - score = score + string.byte(char) - string.byte("A") + 27 - goto continue - elseif char == string.lower(char) then - score = score + string.byte(char) - string.byte("a") + 1 - goto continue - end - end - - end - - ::continue:: + score = score + find_duplicates(one, two, three) end print(score)