Corona SDK – Shuffle Array Elements

Corona SDK Array Shuffle - Featured Image

Shuffling elements in array is very important for many of apps like Word Games. The function isn’t just for Corona but the same logic can be used for any other programming language.

// This used math.random function to shuffle. Math.random is a function that gives a random number every time you call the function in Corona.

local shuffle = {}
local array1 = {1,2,3,4,5,6,7,8,9}

function shuffle(t1)
  local n1 = #t1
  while n1 >= 2 do
    local k1 = math.random(n1)
    t1[n1], t1[k1] = t1[k1], t1[n1]
    n1 = n1 - 1
 return t1

array1 = shuffle(array1)

print("Shuffled Array")
for i=1,#array1 do

This way you can write a shuffle function to shuffle the elements in an array.

Corona SDK Array Shuffle

Corona SDK Array Shuffle


Some classic examples of using shuffle function is for Word Shuffle Apps.

Please let us know if you have shuffled the array elements better than this.