Expectable JavaScript array shuffling

Is there a way to consistently shuffle javascript arrays with the same result every time the webpage is loaded?

Even though I can shuffle the arrays randomly, each page reload yields a different sequence.

I'm looking for a solution that will shuffle the arrays in a consistent manner every time the page is loaded. These arrays play a crucial role in generating a procedural virtual world.

Answer №1

Billy Moon, I am grateful that Chance.js performed flawlessly for me.

Here is an example from my experience:

<script type="text/javascript" src="assets/js/chance.js"></script>

var chance1 = new Chance(124); // I chose 124 as the seed
console.log(chance1.shuffle(['alpha', 'bravo', 'charlie', 'delta', 'echo']));
// Result: [ "alpha", "delta", "echo", "charlie", "bravo" ]

By setting the seed with new Chance(xxx), you can consistently obtain the same outcome each time.

Answer №2

To achieve a random and predetermined shuffling of an array, the process can be divided into two main steps.

1. Generating pseudo-random numbers

While there are various options for PRNGs, the Xorshift algorithm stands out for its simplicity, speed in initialization and iteration, as well as uniform distribution.

This function requires an integer seed value and produces a random function that consistently generates floating-point values between 0 and 1.

const xor = seed => {
  const baseSeeds = [123456789, 362436069, 521288629, 88675123]

  let [x, y, z, w] = baseSeeds

  const random = () => {
    const t = x ^ (x << 11)
    ;[x, y, z] = [y, z, w]
    w = w ^ (w >> 19) ^ (t ^ (t >> 8))
    return w / 0x7fffffff
  }

  ;[x, y, z, w] = baseSeeds.map(i => i + seed)
  ;[x, y, z, w] = [0, 0, 0, 0].map(() => Math.round(random() * 1e16))

  return random
}

2. Shuffling using a customizable random function

The Fisher Yates shuffle is a highly efficient shuffling technique with a uniform distribution.

const shuffle = (array, random = Math.random) => {
  let m = array.length
  let t
  let i

  while (m) {
    i = Math.floor(random() * m--)
    t = array[m]
    array[m] = array[i]
    array[i] = t
  }

  return array
}

Bringing it all together

// Using the same seed for xor will yield the same shuffled output
console.log(shuffle([1, 2, 3, 4, 5, 6, 7, 8, 9], xor(1))) // [ 3, 4, 2, 6, 7, 1, 8, 9, 5 ]
console.log(shuffle([1, 2, 3, 4, 5, 6, 7, 8, 9], xor(1))) // [ 3, 4, 2, 6, 7, 1, 8, 9, 5 ]

// Changing the seed provided to the xor function results in a different output
console.log(shuffle([1, 2, 3, 4, 5, 6, 7, 8, 9], xor(2))) // [ 4, 2, 6, 9, 7, 3, 8, 1, 5 ]

Answer №3

Check out the seed function on chancejs.com for more information.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

What is the best way to submit updated data from an Angular form?

Currently, I have a situation where multiple forms are connected to a backend service for storing data. My query is whether there exists a typical angular method to identify which properties of the model have been altered and only send those in the POST r ...

The PHP header() function is not properly redirecting the page, instead it is only displaying the HTML

After double checking that no client sided data was being sent beforehand and enabling error reporting, I am still encountering issues. The issue revolves around a basic login script with redirection upon validation. <?php include_once "database- ...

The combination of Array map and reduce results in an unexpected undefined output

I have a pair of arrays known as headersMap and selected_arr structured in the following manner: headersMap: [ { text: "#", align: "center", sortable: true, value: "id", align: "start&quo ...

Exploring the .map() Method in ReactJS

Would it be feasible to integrate another Postgres database table into the current mapping displayed in this code? It would be ideal if it could be done using some sort of array function. {items.map(item => ( <tr key={item.id}& ...

Is it possible to provide unrestricted support for an infinite number of parameters in the typing of the extend function from Lodash

I am utilizing the "extend" function from lodash to combine the objects in the arguments as follows: import { extend } from 'lodash'; const foo1 = { item: 1 }; const foo2 = { item: 1 }; const foo3 = { item: 1 }; const foo4 = { item: 1 }; const f ...

Concealing Worksheets When Workbook is Opened

I came across this code online claiming that it works, but I am having trouble with it. The code involves looping to unhide elements, but I am trying to hide them instead. Why isn't this working? Also, should I just adjust the dimensions of the Listbo ...

Error: The function gethostname has not been declared

I attempted to set a variable using gethostname() (1) and with $_SERVER(2), but I always receive an error message saying ReferenceError: gethostname is not defined. My goal is simply to fetch the current system name into a variable using JavaScript within ...

Ways to pass scope between the same controller multiple times

There is a unique scenario in which I have a controller appearing in 2 different locations on a page. This arrangement is necessary for specific reasons. To illustrate, the simplified HTML structure is as follows: <aside ng-if="aside.on" ng-controller ...

Tips for adding text dynamically to images on a carousel

The carousel I am using is Elastislide which can be found at http://tympanus.net/Development/Elastislide/index.html. Currently, it displays results inside the carousel after a search, but I am struggling to dynamically add text in order to clarify to use ...

Creating arrays in Python 3: A Beginner's Guide

I am struggling to declare an array in Python3 and keep encountering errors. Python 3.6.7 (default, Oct 22 2018, 11:32:17) [GCC 8.2.0] on linux Type "help", "copyright", "credits" or "license" for more information. >>> numbers=[] >>> num ...

``Is there a more SEO-friendly option instead of using an iframe?

I am looking for a solution to easily share my content with other websites without the issues I currently face. Presently, I use an iframe which poses two problems: <iframe width=“540”; height=“700” frameborder=“0” src=“http://www.energi ...

"Error: The $ variable is not defined" - encountered while working with a date-time picker in Jade/Pug

I am attempting to implement a date/time picker in jade/pug that resembles the example provided on this page: . I am working with a Node/express js server. However, when I click on the glyphicon-calendar icon, the calendar fails to display. I have already ...

Tips on Including Service in Angular Testing Specification File with Jasmin/Karma

I'm a beginner when it comes to writing unit tests for Angular. I have a scenario where I need to inject a service into my controller file (.ts). How can I go about injecting the service file in the spec file? Below is the code snippet: app.componen ...

What is the reason behind including a data string filled with a series of numbers accompanied by dashes in this ajax request?

I stumbled upon a website filled with engaging JavaScript games and was intrigued by how it saves high scores. The code snippet in question caught my attention: (new Request({ url: window.location.toString().split("#")[0], data: { ...

What is the best way to customize multiple checkboxes in React Native?

I need help with implementing checkboxes in my app using react-native-check-box. I have tried creating 4 checkboxes, but the text inside them is not aligning properly. The boxes are rendering one above the other instead of staying on the same line. I want ...

Many inhabitants - utilizing mongoosejs

Just a simple question, for example with a double reference in the model. Schema / Model var OrderSchema = new Schema({ user: { type : Schema.Types.ObjectId, ref : 'User', required: true }, meal: { ...

Highcharts displaying black color after AJAX refresh

Struggling to implement real-time data visualization using Highcharts, I found myself tired of sifting through documentation and feeling confused. My solution involves using AJAX refresh. When the page initially reloads, my chart renders properly. However, ...

Turning off and on CSS transitions to set the initial position

Is there a way in javascript to position divs with rotations without using transitions initially for an animation that will be triggered later by css transition? I have tried a codepen example which unfortunately does not work on the platform but works fin ...

Tips for successfully sending data to an ng-include controller

So, I've got this ng-include html element, and I'm trying to figure out how to pass data from an external source to the controller. The primary controller is responsible for fetching json data from a http webservice, and then parsing that data i ...

What is the best way to evaluate two objects with varying data types?

Is it possible to compare two objects with different data types? var a = { sort: 7, start: "0"} var b = { sort: "7", start: "0"} I thought they should be equal, but when I try using JSON.stringify(a) === JSON.stringify(b), it returns false. ...