Skip to content
programming languages for all
GitHub

Matrix in Lua

문제

Matrix in LuaYou have stumbled upon a group of mathematicians who are also singer-songwriters.

참고할 자료와 개념

풀이된 예제

명령형

return function(s)
    ---@type number[][]
    local rows = {}

    for line in s:gmatch('[%d ]+') do
        local row = {}
        for r in line:gmatch('%d+') do table.insert(row, tonumber(r)) end
        table.insert(rows, row)
    end

    return {
        row = function(index) return rows[index] end,
        column = function(index)
            local result = {}
            for _, r in ipairs(rows) do
                table.insert(result, r[index])
            end
            return result
        end
    }
end

-- 4 successes / 0 failures / 0 errors / 0 pending : 0.000674 seconds

함수형

local function map(table, f)
    local t = {}
    for k, v in pairs(table) do t[k] = f(v) end
    return t
end

local function split(s, sep)
    if sep == nil then sep = "%s" end
    local t = {}
    for str in string.gmatch(s, "([^" .. sep .. "]+)") do
        table.insert(t, str)
    end
    return t
end

return function(s)
    ---@type number[][]
    local rows = map(split(s, "\n"), function(line)
        return map(split(line, " "), function(n) return tonumber(n) end)
    end)

    return {
        ---@return number[]
        row = function(index) return rows[index] end,
        ---@return number[]
        column = function(index)
            return map(rows, function(row) return row[index] end)
        end
    }
end

-- 4 successes / 0 failures / 0 errors / 0 pending : 0.000671 seconds