Saturday, February 25, 2023

D3.js visual shuffle

 Fisher–Yates Shuffle

function shuffle(array) {
  var m = array.length, t, i;
  // While there remain elements to shuffle…
  while (m) {
    // Pick a remaining element…
    i = Math.floor(Math.random() * m--);
    // And swap it with the current element.
    t = array[m];
    array[m] = array[i];
    array[i] = t;
  return array;
For more about the Fisher–Yates shuffle, see the Wikipedia article and Jeff Atwood’s post, “The Danger of Naïveté” (2007). The visualizations in this post were built with d3.js and inspired by sort algorithm visualizations in Robert Sedgewick’s Algorithms in C (1998). See as well these visualizations of merge sort and quicksort.
How to randomize (shuffle) a JavaScript array? - Stack Overflow
array.sort(() => Math.random() - 0.5)