How to resolve the algorithm Knuth shuffle step by step in the Crystal programming language
Published on 12 May 2024 09:40 PM
How to resolve the algorithm Knuth shuffle step by step in the Crystal 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 Crystal programming language
Source code in the crystal programming language
def knuthShuffle(items : Array)
i = items.size-1
while i > 1
j = Random.rand(0..i)
items.swap(i, j)
i -= 1
end
end
You may also check:How to resolve the algorithm Harshad or Niven series step by step in the AppleScript programming language
You may also check:How to resolve the algorithm Catalan numbers/Pascal's triangle step by step in the Vala programming language
You may also check:How to resolve the algorithm Word frequency step by step in the C++ programming language
You may also check:How to resolve the algorithm Combinations step by step in the Julia programming language
You may also check:How to resolve the algorithm Main step of GOST 28147-89 step by step in the JavaScript programming language