lua-users home
lua-l archive

[Date Prev][Date Next][Thread Prev][Thread Next] [Date Index] [Thread Index]


On Tue, Dec 8, 2020 at 4:37 PM Chris Smith wrote:
An emulation could be created in 0.00 seconds  ;-)
Prove it. :)  

function solution(level)
   local t = {"Lua"}
   local mod = (2<<level)-1
   if level > 0 then
      setmetatable(t, {__index =
         function (_, k)
            local m = mod
            if k%m == k then
               while k > 2 do
                  m, k = m>>1, k%m
               end
               if k ~= 0 then
                  return "Lua"
               end
            end
         end
      })
   end
   local last_index = mod - level
   return t, last_index
end

local level = tonumber(arg[1])
local t, last_index = solution(level)


 
If it walks like a duck and quacks like a duck….

It might still not be a duck.

 
this simpler version which does exactly what you ask:

Clever idea with weak tables!
But you have to invoke collectgarbage() before exiting from solution4()
Otherwise t contains your pseudo-nil-table instead of nil.

$ time lua xmilia_loop100.lua 20
real    0m12.336s
 
$ time lua chris_loop100.lua 20
real    0m10.267s

You're the new winner!