How to resolve the algorithm Knuth shuffle step by step in the AWK programming language
Published on 12 May 2024 09:40 PM
How to resolve the algorithm Knuth shuffle step by step in the AWK 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 AWK programming language
Source code in the awk programming language
# Shuffle an _array_ with indexes from 1 to _len_.
function shuffle(array, len, i, j, t) {
for (i = len; i > 1; i--) {
# j = random integer from 1 to i
j = int(i * rand()) + 1
# swap array[i], array[j]
t = array[i]
array[i] = array[j]
array[j] = t
}
}
# Test program.
BEGIN {
len = split("11 22 33 44 55 66 77 88 99 110", array)
shuffle(array, len)
for (i = 1; i < len; i++) printf "%s ", array[i]
printf "%s\n", array[len]
}
You may also check:How to resolve the algorithm Leap year step by step in the Vedit macro language programming language
You may also check:How to resolve the algorithm Boustrophedon transform step by step in the Nim programming language
You may also check:How to resolve the algorithm Remove duplicate elements step by step in the GAP programming language
You may also check:How to resolve the algorithm Active object step by step in the E programming language
You may also check:How to resolve the algorithm Amb step by step in the ATS programming language