Top community members
All Wiki Articles Create Wiki Article

Many years me and my friends we were volunteers on my university doing programming classes for young people.

I got main conclusion: Young people are awesome, especially students, because they always bring new and fresh ideas :)
* I loved to do it but my time is limited

  I decided to create something that will help millions of students

Now I am here

co-founder

JavaScript - own random number generator (custom implementation)

0 contributions
11 points

In this article, we're going to have a look at how to write own random numbers genrator that is based onĀ LCG (Linear congruential generator) algorithmĀ in JavaScript.

1. Introduction

In JavaScript we can implement custom random number generator by using LCG (Linear congruential generator) algorithm. LCG is one of the oldest and best-known pseudorandom number generator algorithm. We can adjust this implementation to work on int or long.

Linear congruential generator is defined by recurrence relation:

Where:

  • Xn+1 - new seed
  • a -Ā MULTIPLIER_A
  • XnĀ - current seed field
  • c -Ā INCREMENT_C
  • m -Ā MODULUS

2. Implementation

Note: every time randomInt() method is called, it is necessary to updateĀ seed value.

// ONLINE-RUNNER:browser;

function RandomUtil(seed) {
    var self = this;

    if (seed == null) {
        seed = 3819201;
    }

    var MULTIPLIER_A = 1103515245;
    var INCREMENT_C = 12345;
    var MODULUS = 2147483647; // max integer value

    self.randomInt = function() {
        seed = (seed * MULTIPLIER_A + INCREMENT_C) % MODULUS;
        return seed;
    };
}

// Usage example 1:

var util = new RandomUtil();

console.log(util.randomInt()); // 348328093
console.log(util.randomInt()); // 121065958
console.log(util.randomInt()); // 790325445

// Usage example 2:

var now = new Date();
var util = new RandomUtil(now.getTime());

// Values should be different always:
console.log(util.randomInt()); // 922892575
console.log(util.randomInt()); // 1117277734
console.log(util.randomInt()); // 2084933141
0 contributions

Suggested wiki articles:

Suggested findings

Let's do the work and have some fun
  • Dirask is online IT community for professionals and hobbyist to share their knowledge and help each other in extraordinary easy way. ā¤ šŸ’» šŸ™‚
  • We welcome everyone,
    no matter what the experience,
    no matter how basic the question is,
    we will help you. šŸ‘ āœ” šŸ¦„
Read more