Advertisement
InTesting

Number Base System Polished

Oct 5th, 2021
779
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Lua 1.60 KB | None | 0 0
  1. -- functions
  2. function splitChars(str)
  3.     str = tostring(str)
  4.    
  5.     return str:split''
  6. end
  7.  
  8. function flipTable(t)
  9.     local t2 = {}
  10.    
  11.     for i, v in next, t do
  12.         t2[v] = i
  13.     end
  14.    
  15.     return t2
  16. end
  17.  
  18. function arrayToCharDict(arr)
  19.     local dict = {}
  20.    
  21.     for i, v in next, arr do
  22.         dict[i - 1] = v
  23.     end
  24.    
  25.     return dict
  26. end
  27.  
  28. function stringToCharDict(str)
  29.     return arrayToCharDict(splitChars(str))
  30. end
  31.  
  32. --  base system
  33. function factNumToStrFromBase(charsDict)
  34.     local base = #charsDict + 1
  35.    
  36.     return function(num)
  37.         local res = ''
  38.  
  39.         local iterations = 1 + math.max(0, math.floor( math.log(num, base)))
  40.  
  41.         for i = iterations, 1, -1  do -- going down number places
  42.             local factor = base ^ (i - 1)
  43.  
  44.             local index = base - 1
  45.  
  46.             for largestDigit = base, 0, -1 do -- going down the base to 1
  47.                 local num2 = factor * largestDigit
  48.  
  49.                 if num - num2 < 0 then continue end
  50.  
  51.                 index = largestDigit
  52.                 num -= num2
  53.  
  54.                 break
  55.             end
  56.             res ..= charsDict[index]
  57.         end
  58.  
  59.         return res
  60.     end
  61. end
  62.  
  63. function factStrToNumFromBase(charsDict)
  64.     local base = #charsDict + 1
  65.     local flippedCharacters = flipTable(charsDict)
  66.  
  67.     return function(str)
  68.         local res = 0
  69.  
  70.         for index = 1, #str do -- iterate each letter
  71.             local letter = str:sub(index, index)
  72.            
  73.             local num = flippedCharacters[letter] * base ^ (#str - index)
  74.            
  75.             res += num
  76.         end
  77.  
  78.         return res
  79.     end
  80. end
  81.  
  82. local binary = stringToCharDict'01'
  83.  
  84. local numToStr_Bin = factNumToStrFromBase(binary)
  85. local strToNum_Bin = factStrToNumFromBase(binary)
  86.  
  87.  
  88. for n = 1, 10 do
  89.     local s = numToStr_Bin(n)
  90.    
  91.     print(n, s, strToNum_Bin(s))
  92. end
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement