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

Published on 12 May 2024 09:40 PM

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

Source code in the sparforte programming language

#!/usr/local/bin/spar
pragma annotate( summary, "shuffle" );
pragma annotate( description, "Implement the Knuth shuffle (aka the" );
pragma annotate( description, "Fisher-Yates-Durstenfeld shuffle)" );
pragma annotate( description, "for an integer array (or, if possible, an array of any" );
pragma annotate( description, "type). The Knuth shuffle is used to create a random" );
pragma annotate( description, "permutation of an array." );
pragma annotate( description, "Note: spar has a built-in arrays.shuffle() function that does this." );
pragma annotate( see_also, "http://rosettacode.org/wiki/Knuth_shuffle" );
pragma annotate( author, "Ken O. Burtch" );
pragma license( unrestricted );

pragma restriction( no_external_commands );

procedure shuffle is

  subtype array_element_type is string;
  type magic_items is array(1..3) of array_element_type;

  a : magic_items := ( "bell", "book", "candle" );
  t : array_element_type;
  k : integer;

begin

  for i in reverse arrays.first( a ) .. arrays.last( a )-1 loop
    k := integer( numerics.rnd( i+1 ) ) - 1 + arrays.first(a);
    t := a(i);
    a(i) := a(k);
    a(k) := t;
  end loop;

  for i in arrays.first( a ) .. arrays.last( a ) loop
    ? a(i);
  end loop;

end shuffle;

  

You may also check:How to resolve the algorithm Copy a string step by step in the Lambdatalk programming language
You may also check:How to resolve the algorithm Singly-linked list/Traversal step by step in the Julia programming language
You may also check:How to resolve the algorithm Filter step by step in the Nim programming language
You may also check:How to resolve the algorithm Higher-order functions step by step in the Luck programming language
You may also check:How to resolve the algorithm Program termination step by step in the Rust programming language