Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- -- functions
- function splitChars(str)
- str = tostring(str)
- return str:split''
- end
- function flipTable(t)
- local t2 = {}
- for i, v in next, t do
- t2[v] = i
- end
- return t2
- end
- function arrayToCharDict(arr)
- local dict = {}
- for i, v in next, arr do
- dict[i - 1] = v
- end
- return dict
- end
- function stringToCharDict(str)
- return arrayToCharDict(splitChars(str))
- end
- -- base system
- function factNumToStrFromBase(charsDict)
- local base = #charsDict + 1
- return function(num)
- local res = ''
- local iterations = 1 + math.max(0, math.floor( math.log(num, base)))
- for i = iterations, 1, -1 do -- going down number places
- local factor = base ^ (i - 1)
- local index = base - 1
- for largestDigit = base, 0, -1 do -- going down the base to 1
- local num2 = factor * largestDigit
- if num - num2 < 0 then continue end
- index = largestDigit
- num -= num2
- break
- end
- res ..= charsDict[index]
- end
- return res
- end
- end
- function factStrToNumFromBase(charsDict)
- local base = #charsDict + 1
- local flippedCharacters = flipTable(charsDict)
- return function(str)
- local res = 0
- for index = 1, #str do -- iterate each letter
- local letter = str:sub(index, index)
- local num = flippedCharacters[letter] * base ^ (#str - index)
- res += num
- end
- return res
- end
- end
- local binary = stringToCharDict'01'
- local numToStr_Bin = factNumToStrFromBase(binary)
- local strToNum_Bin = factStrToNumFromBase(binary)
- for n = 1, 10 do
- local s = numToStr_Bin(n)
- print(n, s, strToNum_Bin(s))
- end
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement