Module:Array

From ropewiki.com
Jump to navigation Jump to search

Documentation for this module may be created at Module:Array/doc


local array = {}

-- input array is sent as a string, need to convert it to a table
-- example input: "2.1<PROP>1, 3.7<PROP>3, 3.2<PROP>4, 2.4<PROP>2
local function createTableFromCommaString(inputString)
    local luaTable = {}
    
    -- Split the inputString into elements using a comma as the delimiter
    for element in inputString:gmatch("([^,]+)") do

        local num, propCount = element:match("([^<]+)<PROP>(%d+)")

        -- Trim leading and trailing spaces using a regular expression
        num = tonumber(num:match("^%s*(.-)%s*$"))
        propCount = tonumber(propCount:match("^%s*(.-)%s*$"))

        if num and propCount then
            for i = 1, propCount do
                table.insert(luaTable, num)
            end
        end
    end
    
    return luaTable
end

-- Function to calculate winsorized mean
function array.winsorized_mean(frame)
    local trim_percent = tonumber( frame.args[2] )
    local data = createTableFromCommaString(frame.args[1])

    -- Ensure the trim_percent is within the valid range (0 to 0.5)
    trim_percent = math.max(0, math.min(trim_percent, 0.5))

    -- Sort the data
    table.sort(data)

    -- Calculate the number of elements to trim from each end
    local trim_count = math.floor(#data * trim_percent)

    -- Replace values at the lower and upper tails
    for i = 1, trim_count do
        data[i] = data[trim_count + 1]
        data[#data - i + 1] = data[#data - trim_count]
    end

    -- Calculate the mean of the remaining values
    local sum = 0
    for i = 1, #data do
        sum = sum + data[i]
    end

    -- Divide by the number of values
    local mean = sum / #data

    --return trim_count
    --return table.concat(data, ", ")
    return mean
    
end

return array