-
Notifications
You must be signed in to change notification settings - Fork 0
/
day4-2.lua
67 lines (58 loc) · 1.67 KB
/
day4-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
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
io.input( "day4-input.txt" )
io.write( "Please enter your puzzle input: (end of file with Ctrl-Z)\n" )
local function countLetters( str )
local letters = {}
for letter in string.gmatch( str, "%l" ) do
if not letters[ letter ] then
letters[ letter ] = 0
end
letters[ letter ] = letters[ letter ] + 1
end
return letters
end
local function isAnagram( letters1, letters2 )
local anagram = true
for letter in pairs( letters1 ) do
if not letters2[ letter ] or letters1[ letter ] ~= letters2[ letter ] then
anagram = false
break
end
end
for letter in pairs( letters2 ) do
if not letters1[ letter ] or letters1[ letter ] ~= letters2[ letter ] then
anagram = false
break
end
end
return anagram
end
local numValid = 0
for line in io.lines() do
local words = {}
local wordLetters = {}
local valid = true
for word1 in string.gmatch( line, "%l+" ) do
local letters1 = countLetters( word1 )
for k, word2 in pairs( words ) do
local letters2 = wordLetters[ k ]
if word1 == word2 then
valid = false
break
elseif isAnagram( letters1, letters2 ) then
-- print( word1 )
-- print( word2 )
valid = false
break
end
end
if not valid then
break
end
table.insert( words, word1 )
table.insert( wordLetters, letters1 )
end
if valid then
numValid = numValid + 1
end
end
io.write( numValid, " passphrases are valid." )