Jump to content

Module:User:Mr. Stradivarius/sandbox

From Wikipedia, the free encyclopedia
This is an old revision of this page, as edited by Mr. Stradivarius (talk | contribs) at 01:49, 26 February 2014 (code for getting capitalisation combinations). The present address (URL) is a permanent link to this revision, which may differ significantly from the current revision.
local function calcLength(num)
	local length
	if num < 0 then
		return nil
	elseif num == 0 then
		length = 1
	else
		length = math.log(num) / math.log(2)
		length = math.floor(length)
		length = length + 1
	end
	return length
end

local function calcPosVal(pos, num)
	local i = math.floor(num / (2 ^ (pos - 1))) % 2
	if i == 0 then
		return false
	elseif i == 1 then
		return true
	else
		error('unexpected value ' .. tostring(i) .. ' from function calcPosVal')
	end
end

local function binaryTable(num, length)
	local length = length or calcLength(num)
	local ret = {}
	for i = 1, length do
		ret[i] = calcPosVal(i, num)
	end
	return ret
end

local function binaryTableArray(length)
	local ret = {}
	for i = 0, 2 ^ length - 1 do
		ret[#ret + 1] = binaryTable(i, length)
	end
	return ret
end

local function codeCombos(code)
	local chars = {}
	for char in string.gmatch(code, '.') do
		chars[#chars + 1] = char
	end
	local comboTables = binaryTableArray(#chars)
	local ret = {}
	for _, t in ipairs(comboTables) do
		local newChars = {}
		for i, char in ipairs(chars) do
			if t[i] then
				newChars[#newChars + 1] = char:upper()
			else
				newChars[#newChars + 1] = char
			end
		end
		ret[table.concat(newChars)] = true
	end
	return ret
end

local p = {}
p.bin = binaryTable
p.array = binaryTableArray
p.combos = codeCombos
return p