Skip to content

Instantly share code, notes, and snippets.

@royratcliffe
Created June 5, 2025 16:43
Show Gist options
  • Save royratcliffe/c3ad9ff6c0aafe35eefdd9f88e680246 to your computer and use it in GitHub Desktop.
Save royratcliffe/c3ad9ff6c0aafe35eefdd9f88e680246 to your computer and use it in GitHub Desktop.
Lua
math.randomseed(os.time() + os.clock() * 100000)
--- Performs an in-place Fisher-Yates shuffle on the given array.
-- This function implements the Fisher-Yates shuffle algorithm.
-- It randomly shuffles the elements of the array in place, ensuring
-- that each permutation of the array is equally likely.
-- @tparam {[number]=any} arr The array to shuffle.
function fisher_yates_shuffle(arr)
-- No need to shuffle if the array has less than 2 elements.
if #arr < 2 then return end
-- Start at the last index (#arr) and decrement to 2 to ensure all
-- elements are shuffled.
for outer = #arr, 2, -1 do
local inner = math.random(outer)
-- Perform in-place swapping to shuffle the elements.
arr[outer], arr[inner] = arr[inner], arr[outer]
end
end

‎‎​

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment