lua-users home
lua-l archive

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


On 8/07/2015 11:04, Dirk Laurie wrote:
2015-07-07 22:47 GMT+02:00 voidptr <voidptr69@gmail.com>:

    for x = 1, 54 do
         if m[x] == 0 then
             cb[x] = ca[x]
         else
             cb[x] = ca[m[x]]
         end
    end
I'm going a little off-topic on just benchmarking, but it's on-topic on
how cool Lua is.

The above is not the way experienced Lua programmers would code
it.  A move of the Rubik cube affects only 20 of the 54 little squares,
so you could represent it as a non-sequential table containing only
those, e.g.

m = {[3]=1,[6]=2,[9]=3,etc}

Then your loop becomes:

for x=1,54 do  cb[x] = ca[m[x] or x]  end



Well, if you're to copy 54 items anyway, there's a simpler and clearer way:
define m[x] = x instead of m[x] = 0 for x's that don't move,
then your code becomes:

for x = 1,54 do
  cb[x] = ca[m[x]]
end

(Probably significantly faster with compiled languages like LuaJIT and C/C++ since there is no branch prediction involved.)

Frédéric