Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Generate a random number from another number

In JavaScript, is it possible to generate a random number from another number?

I'm trying to implement a predictable random number generator for one of my fractal terrain generators. I already know that it's possible to generate a random number using Math.random(), but I want to create a random number generator that produces exactly one output for every input. (For example, predictableRandomGenerator(1) would always produce the same result, which would not necessarily be the same as the input.)

So is it possible to generate a random number from another number, where the output is always the same for each input?

like image 796
Anderson Green Avatar asked May 25 '13 03:05

Anderson Green


2 Answers

You can use a checksum generator such as MD5 or SHA-1 to generate a single pseudo-random output for every input. SHA-1 will generate a random number from each string that is entered as input, and each output will produce exactly one input. (It's likely that any other checksum generator would be suitable for thus purpose as well, since checksum generators produce exactly one output for each input that is entered).

like image 192
Anderson Green Avatar answered Sep 21 '22 12:09

Anderson Green


Yes, it is possible. However you'll need to write your own pseudo-random number generator.

See, computers can't really generate random numbers. However you can use an algorithm which creates a sequence of numbers which appears to be random.

This algorithm is usually given a seed and each seed leads to a different sequence of random numbers generated by the algorithm.

The most common algorithm is the linear congruential pseudorandom number generator, as defined by D. H. Lehmer and described by Donald E. Knuth in The Art of Computer Programming, Volume 2: Seminumerical Algorithms, section 3.2.1.

For more details refer to the following thread: Predict the Seed of Javascript's Math.random

like image 24
Aadit M Shah Avatar answered Sep 22 '22 12:09

Aadit M Shah