Home > Back-end >  Random integer in the range without random library
Random integer in the range without random library

Time:06-06

I have a question about randomizing a number from a range without using the random library and similar.

I have seen the use of a method to generate noise from a microphone, but it does not have a given range.

Is there anything else? Because I couldn't find any more example of using it with user input (like CPU temp or current date).

CodePudding user response:

Well, this isn't truly random as I mentioned in the comments. But it does what you ask.

  • min - smallest value in range (inclusive)
  • max - largest value in range (exclusive)

So the range is from min to max-1 inclusive.

public static long rand(int min, int max) {
    return (System.nanoTime()%(max-min))   min;
}

CodePudding user response:

You can generate a psudo-random number using a seed based on:

  • Computer hour
  • Computer available disk bits
  • A mix of boths or even other options about computer...

For generating psudo-random numbers nowadays it is most commonly used LFSR (Linear Feedback Shift Register) based on logic operations.

The process would be something like this:

Start with a binary seed like for instance with 5 bits you can generate up to 2^5 -1 random numbers.

Lets put an example. Starting with 01101:

  1. Extract last bit from the seed
  2. Move forward the other bits and do XOR of last 2 bits In this case XOR of 0 & 1 is = 1 the result would be 10110
  3. Repeat this process to generate new numbers this is close to throwing a coin to the air almos random.

More info: https://zipcpu.com/dsp/2017/11/11/lfsr-example.html

  • Related