How to resolve the algorithm Knuth shuffle step by step in the Tcl programming language
Published on 12 May 2024 09:40 PM
How to resolve the algorithm Knuth shuffle step by step in the Tcl 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 Tcl programming language
Source code in the tcl programming language
proc knuth_shuffle lst {
set j [llength $lst]
for {set i 0} {$j > 1} {incr i;incr j -1} {
set r [expr {$i+int(rand()*$j)}]
set t [lindex $lst $i]
lset lst $i [lindex $lst $r]
lset lst $r $t
}
return $lst
}
% knuth_shuffle {1 2 3 4 5}
2 1 3 5 4
% knuth_shuffle {1 2 3 4 5}
5 2 1 4 3
% knuth_shuffle {tom dick harry peter paul mary}
tom paul mary harry peter dick
% for {set i 0} {$i<100000} {incr i} {
foreach val [knuth_shuffle {1 2 3 4 5}] pos {pos0 pos1 pos2 pos3 pos4} {
incr tots($pos) $val
}
}
% parray tots
tots(pos0) = 300006
tots(pos1) = 300223
tots(pos2) = 299701
tots(pos3) = 299830
tots(pos4) = 300240
You may also check:How to resolve the algorithm Symmetric difference step by step in the Groovy programming language
You may also check:How to resolve the algorithm Determine if only one instance is running step by step in the BBC BASIC programming language
You may also check:How to resolve the algorithm Inheritance/Multiple step by step in the Lua programming language
You may also check:How to resolve the algorithm Check input device is a terminal step by step in the Standard ML programming language
You may also check:How to resolve the algorithm Create an HTML table step by step in the Visual Basic .NET programming language