forked from adventofcode/logan_2022
54 lines
1.7 KiB
Lua
54 lines
1.7 KiB
Lua
for i = 1, 1000 do
|
|
-- Open the file for reading
|
|
local file = assert(io.open("strings.txt", "r"))
|
|
|
|
-- Initialize a variable to store the sum of scores
|
|
local score = 0
|
|
|
|
-- Read each line from the file
|
|
for line in file:lines() do
|
|
-- Split the line in half
|
|
local first_half = line:sub(1, #line / 2)
|
|
local second_half = line:sub(#line / 2 + 1)
|
|
|
|
-- Create a table to store the characters in each half
|
|
local first_half_chars = {}
|
|
local second_half_chars = {}
|
|
|
|
-- Iterate over each character in each half and store it in the table
|
|
for i = 1, #first_half do
|
|
first_half_chars[first_half:sub(i, i)] = true
|
|
end
|
|
for i = 1, #second_half do
|
|
second_half_chars[second_half:sub(i, i)] = true
|
|
end
|
|
|
|
-- Create a table to store the characters that have already been counted
|
|
local counted_chars = {}
|
|
|
|
-- Iterate over each character in the first half again
|
|
-- and check if it exists in the second half
|
|
for i = 1, #first_half do
|
|
local char = first_half:sub(i, i)
|
|
if second_half_chars[char] and not counted_chars[char] then
|
|
-- If it does and it hasn't been counted yet,
|
|
-- assign it a score and add it to the sum of scores
|
|
local score_value = 0
|
|
if char:lower() == char then
|
|
-- If the character is lowercase, its score is its ASCII value - 96
|
|
score_value = string.byte(char) - 96
|
|
else
|
|
-- If the character is uppercase, its score is its ASCII value - 64 + 26
|
|
score_value = string.byte(char) - 64 + 26
|
|
end
|
|
score = score + score_value
|
|
|
|
-- Add the character to the counted_chars table so it won't be counted again
|
|
counted_chars[char] = true
|
|
end
|
|
end
|
|
end
|
|
|
|
-- Print the final sum of scores
|
|
print(score)
|
|
end
|