Advertisement
Guest User

Untitled

a guest
Dec 2nd, 2018
131
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Lua 1.38 KB | None | 0 0
  1. function readLinesFromFile(file)
  2.     local fs = assert(io.open(file, "rb"))
  3.     local content = fs:read("*all")
  4.     local lines = {}
  5.    
  6.     fs:close()
  7.  
  8.     for line in content:gmatch("[^\r\n]+") do
  9.         table.insert(lines, line)
  10.     end
  11.  
  12.     return lines
  13. end
  14.  
  15. function tablelength(table)
  16.     local count = 0
  17.    
  18.     for _ in pairs(table) do
  19.         count = count + 1
  20.     end
  21.  
  22.     return count
  23. end
  24.  
  25. function groupByCharacter(word)
  26.     local temp = {}
  27.  
  28.     for j = 1, string.len(word) do
  29.         local character =  string.sub(word, j, j)
  30.  
  31.         if temp[character] == nil then
  32.             temp[character] = 0
  33.         end
  34.  
  35.         temp[character] = temp[character] + 1
  36.     end
  37.  
  38.     return temp
  39. end
  40.  
  41. function containsValue(dict, value)
  42.     for k, v in pairs(dict) do
  43.         if v == value then
  44.             return true
  45.         end
  46.     end
  47.  
  48.     return false
  49. end
  50.  
  51. function main()
  52.     local words = readLinesFromFile("input.txt")
  53.  
  54.     local twos = 0
  55.     local threes = 0
  56.  
  57.     for i = 1, tablelength(words) do
  58.         local word = words[i]
  59.         local occurences = groupByCharacter(word)
  60.  
  61.         if containsValue(occurences, 2) then
  62.             twos = twos + 1
  63.         end
  64.  
  65.         if containsValue(occurences, 3) then
  66.             threes = threes + 1
  67.         end
  68.     end
  69.  
  70.     local checksum = twos * threes
  71.  
  72.     print(checksum)
  73. end
  74.  
  75. main()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement