Source

project-euler / Lua / 042.lua

Full commit
package.path = package.path .. ";" .. "/home/taylor/Programs/Libraries/Lua/?.lua"
require "list"

local f = assert(io.open("042.txt"))
local data = f:read("*all")

function lettercount(word)
    local sum = 0
    for i = 1, word:len() do
        sum = sum + word:byte(i, i) - 64
    end
    return sum
end

function triangle_generator()
    local n = 1
    return coroutine.create(function ()
        while true do
            local answer = 0.5 * n * (n + 1)
            n = n + 1
            coroutine.yield(answer)
        end
    end)
end

local trival = {}
local triangle = triangle_generator()
local num = 0

function print_triangles()
    for i = 1, #trival do
        if trival[i] then
            io.write(" " .. i)
        end
    end
end

function register_trival(x)
    for i = #trival + 1, x - 1 do
        trival[i] = false
    end
    trival[x] = true
end

for word in string.gmatch(data, '[A-Za-z]+') do
    local count = lettercount(word)
    if trival[count] == nil then
        local status, x = coroutine.resume(triangle)
        if not status then error("Coroutine failed!") end
        while x < count do
            register_trival(x)
            status, x = coroutine.resume(triangle)
            if not status then error("Coroutine failed!") end
        end
        register_trival(x)
        print("Expanded triangle values up to " .. x)
    end
    if trival[count] then
        num = num + 1
    end
end

io.write("Found trivals: ")
print_triangles()
print()
print("Found " .. num .. " triangle words.")