How to resolve the algorithm Knuth shuffle step by step in the Racket programming language
Published on 12 May 2024 09:40 PM
How to resolve the algorithm Knuth shuffle step by step in the Racket 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 Racket programming language
Source code in the racket programming language
#lang racket
(define (swap! vec i j)
(let ([tmp (vector-ref vec i)])
(vector-set! vec i (vector-ref vec j))
(vector-set! vec j tmp)))
(define (knuth-shuffle x)
(if (list? x)
(vector->list (knuth-shuffle (list->vector x)))
(begin (for ([i (in-range (sub1 (vector-length x)) 0 -1)])
(define r (random (+ i 1)))
(swap! x i r))
x)))
(knuth-shuffle '(1 2 3 4))
You may also check:How to resolve the algorithm Factorial step by step in the Zig programming language
You may also check:How to resolve the algorithm Largest proper divisor of n step by step in the Ring programming language
You may also check:How to resolve the algorithm Hello world/Standard error step by step in the Java programming language
You may also check:How to resolve the algorithm Averages/Arithmetic mean step by step in the EDSAC order code programming language
You may also check:How to resolve the algorithm Solve a Hopido puzzle step by step in the Racket programming language