Originally published here at xtrp.io, my blog about computer science and just about anything programming.
Random seed is a method of initializing random number generators using an initial seed value. Random generators with the same seed will output the same pseudo-random results.
I found this method to be particularly useful when developing a game I'm working on, which has a random 'Daily Challenge'. In this case, random seed can be useful to select a random game using the current date as a seed.
So, here's how to create a random seed in Node.js, using the seedrandom NPM package:
// In Node.js const seedrandom = require('seedrandom'); const generator = seedrandom('[your seed here]'); const randomNumber = generator();
And if you're on the client-side:
// On The Browser const generator = new Math.seedrandom('[your seed here]'); const randomNumber = generator();
In both of these code snippets, the
generator function will return a new random number each time, given the seed the generator was initialized with. In this case, it will be formatted as a numerical value, although
If you're running on Node.js, download the seedrandom package as follows:
npm install seedrandom
Or using Yarn:
yarn add seedrandom
If you're writing client-side code without webpack, you can either download the file from seedrandom's GitHub repository, or use a CDN by adding the following code snippet at the end of your
I hope this helps, and thanks for scrolling.
This post is originally from my blog at xtrp.io.
— Gabriel Romualdo, March 26, 2021