0

I want to generate a "random" number between a range, but I need the "random" number to always be the same, according to the parameter (Not exactly "random" :)

With a function like: getRandomInRange(min, max, index)

This needs to be the result:

a = getRandomInRange(100, 600, 1) -> 432
b = getRandomInRange(100, 600, 32) -> 164

a = getRandomInRange(100, 600, 1) -> 432
b = getRandomInRange(100, 600, 32) -> 164

Calling the function with the same index should produce the same value, but the returned number shouldn't necessarily be higher because the index is higher or lower because the index is lower. It should be as random as possible.

Ethan
  • 163
  • 2
  • 12
  • 1
    What about hashing the parameters, then using sum and modulo to make it fit in the range? – Christian Vincenzo Traina Jul 25 '23 at 08:25
  • What have you tried so far? Add a [mcve] to the question – evolutionxbox Jul 25 '23 at 08:25
  • I'd suggest reading up on [seeding random numbers](https://stackoverflow.com/questions/521295/seeding-the-random-number-generator-in-javascript) – Reyno Jul 25 '23 at 08:26
  • Related: https://stackoverflow.com/q/521295/519413 – Rory McCrossan Jul 25 '23 at 08:26
  • Didn't know this was called "seeding", thanks – Ethan Jul 25 '23 at 08:27
  • I was writing an answer but the question got closed in the while. I don't think it's a duplicate, however I'll try to paste my answer in the comments section – Christian Vincenzo Traina Jul 25 '23 at 08:31
  • As stated in my comment, I think the best idea is to hash your parameters and then use sum and modulo to make the result fit in the range. Note that, usually, using a hash function to generate random numbers is not a good idea. However, many hash functions are mathematically similar to pseudorandom number generators. You can use [this answer](https://stackoverflow.com/questions/6122571/simple-non-secure-hash-function-for-javascript) to have a hash function then use it like this: – Christian Vincenzo Traina Jul 25 '23 at 08:38
  • `function getRandomInRange(min, max, index) { return Math.abs(hashCode('' + min + max + index) % (max - min)) + min; }` – Christian Vincenzo Traina Jul 25 '23 at 08:38
  • You might look at this for a well-written random implementation with a seed generator: https://github.com/nquinlan/better-random-numbers-for-javascript-mirror. – Scott Sauyet Jul 25 '23 at 15:07

0 Answers0