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

Published on 12 May 2024 09:40 PM

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

Source code in the coffeescript programming language

knuth_shuffle = (a) ->
  n = a.length
  while n > 1
    r = Math.floor(n * Math.random())
    n -= 1
    [a[n], a[r]] = [a[r], a[n]]
  a

counts =
  "1,2,3": 0
  "1,3,2": 0
  "2,1,3": 0
  "2,3,1": 0
  "3,1,2": 0
  "3,2,1": 0

for i in [1..100000]
  counts[knuth_shuffle([ 1, 2, 3 ]).join(",")] += 1

for key, val of counts
  console.log "#{key}: #{val}"


  

You may also check:How to resolve the algorithm Speech synthesis step by step in the PARI/GP programming language
You may also check:How to resolve the algorithm Elementary cellular automaton/Infinite length step by step in the Phix programming language
You may also check:How to resolve the algorithm Higher-order functions step by step in the Lily programming language
You may also check:How to resolve the algorithm 99 bottles of beer step by step in the Rascal programming language
You may also check:How to resolve the algorithm Image noise step by step in the Go programming language