How to resolve the algorithm Knuth shuffle step by step in the bc programming language
Published on 12 May 2024 09:40 PM
How to resolve the algorithm Knuth shuffle step by step in the bc 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 bc programming language
Source code in the bc programming language
seed = 1 /* seed of the random number generator */
scale = 0
/* Random number from 0 to 32767. */
define rand() {
/* Formula (from POSIX) for random numbers of low quality. */
seed = (seed * 1103515245 + 12345) % 4294967296
return ((seed / 65536) % 32768)
}
/* Shuffle the first _count_ elements of shuffle[]. */
define shuffle(count) {
auto b, i, j, t
i = count
while (i > 0) {
/* j = random number in [0, i) */
b = 32768 % i /* want rand() >= b */
while (1) {
j = rand()
if (j >= b) break
}
j = j % i
/* decrement i, swap shuffle[i] and shuffle[j] */
t = shuffle[--i]
shuffle[i] = shuffle[j]
shuffle[j] = t
}
}
/* Test program. */
define print_array(count) {
auto i
for (i = 0; i < count - 1; i++) print shuffle[i], ", "
print shuffle[i], "\n"
}
for (i = 0; i < 10; i++) shuffle[i] = 11 * (i + 1)
"Original array: "; trash = print_array(10)
trash = shuffle(10)
"Shuffled array: "; trash = print_array(10)
quit
You may also check:How to resolve the algorithm Perfect numbers step by step in the COBOL programming language
You may also check:How to resolve the algorithm Reflection/List methods step by step in the D programming language
You may also check:How to resolve the algorithm Modular exponentiation step by step in the Arturo programming language
You may also check:How to resolve the algorithm Intersecting number wheels step by step in the zkl programming language
You may also check:How to resolve the algorithm Sort numbers lexicographically step by step in the MUMPS programming language