Generating Anagrams in Lua

Mon 22 October 2012 Lua

I’m working on a game where I need to generate anagrams of words. My new game engine, which is Max Astro’s engine but with a few tweeks, integrates Lua and all the game logic is in Lua.

So given a string like “chicken” I want “kcehcine” or some other random reorganisation of the letters in chicken.

Firstly, accessing the individual letters in a Lua string is not that easy, there is no subscript access so I needed to turn the string in to a table:

1
2
3
4
5
local word = "chicken"
local letters = {}
for st in word:gmatch(".") do
    table.insert(letters, st)
end

Now the table letters has all the letters in the word chicken in order. Now I shuffle the table using my table_shuffle function :

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
function table_shuffle(t)
    local n = #t
    while n >= 2 do
        -- n is now the last pertinent index
        local k = math.random(n)
        -- Quick swap
        t[n], t[k] = t[k], t[n]
        n = n - 1
    end
    return t
end

You can turn the table back in to a string using table.concat.

I’m not sure how efficient this is but it suits my needs, I don’t call it often.

The table shuffle function came from here which is an implementation of the Fischer-Yates shuffle algorithm.