How to resolve the algorithm Knuth shuffle step by step in the Lua programming language
Published on 12 May 2024 09:40 PM
How to resolve the algorithm Knuth shuffle step by step in the Lua programming language
Table of Contents
Problem Statement
The Knuth shuffle (a.k.a. the Fisher-Yates shuffle) is an algorithm for randomly shuffling the elements of an array.
Implement the Knuth shuffle for an integer array (or, if possible, an array of any type).
Given an array items with indices ranging from 0 to last, the algorithm can be defined as follows (pseudo-code):
(These are listed here just for your convenience; no need to demonstrate them on the page.)
Let's start with the solution:
Step by Step solution about How to resolve the algorithm Knuth shuffle step by step in the Lua programming language
Source code in the lua programming language
function table.shuffle(t)
for n = #t, 1, -1 do
local k = math.random(n)
t[n], t[k] = t[k], t[n]
end
return t
end
math.randomseed( os.time() )
a = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10}
table.shuffle(a)
for i,v in ipairs(a) do print(i,v) end
You may also check:How to resolve the algorithm 21 game step by step in the Haskell programming language
You may also check:How to resolve the algorithm Perfect shuffle step by step in the VBA programming language
You may also check:How to resolve the algorithm Prime decomposition step by step in the Nim programming language
You may also check:How to resolve the algorithm Deal cards for FreeCell step by step in the Phix programming language
You may also check:How to resolve the algorithm ABC problem step by step in the MiniScript programming language