How to resolve the algorithm Knuth shuffle step by step in the Forth programming language

Published on 12 May 2024 09:40 PM

How to resolve the algorithm Knuth shuffle step by step in the Forth 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 Forth programming language

Source code in the forth programming language

include random.fs

: shuffle ( deck size -- )
  2 swap do
    dup i random cells +
    over @ over @  swap
    rot  ! over !
    cell+
  -1 +loop drop ;

: .array   0 do dup @ . cell+ loop drop ;

create deck 1 , 2 , 3 , 4 , 5 , 6 , 7 , 8 , 9 , 10 ,

deck 10 2dup shuffle .array


  

You may also check:How to resolve the algorithm Loops/For with a specified step step by step in the EMal programming language
You may also check:How to resolve the algorithm UPC step by step in the Java programming language
You may also check:How to resolve the algorithm Taxicab numbers step by step in the zkl programming language
You may also check:How to resolve the algorithm Loops/For step by step in the SNUSP programming language
You may also check:How to resolve the algorithm First-class functions/Use numbers analogously step by step in the Erlang programming language