Skip to main content

Random integer in the range without random library

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).

Answer

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;
}

Comments