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 |
|
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 |
|
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.
Comments