How can I generate a random number without using Math.Random?

My project implies that I am creating a basic number guessing game that uses JOptionPane and does not use Math.Random to create a random value. How would you do that? I have completed everything except the random number generator. Thanks!

+4
source share
5 answers

Here is the code of a simple random generator:

public class SimpleRandom { /** * Test code */ public static void main(String[] args) { SimpleRandom rand = new SimpleRandom(10); for (int i = 0; i < 25; i++) { System.out.println(rand.nextInt()); } } private int max; private int last; // constructor that takes the max int public SimpleRandom(int max){ this.max = max; last = (int) (System.currentTimeMillis() % max); } // Note that the result can not be bigger then 32749 public int nextInt(){ last = (last * 32719 + 3) % 32749; return last % max; } } 

The code above is a β€œLinear Congruent Generator (LCG)”, you can find a good description of how it works here.

Legal information:

The above code is for research use only and not for replacement to a random case or SecureRandom.

+8
source

JavaScript uses the Middle-square method.

 var _seed = 1234; function middleSquare(seed){ _seed = (seed)?seed:_seed; var sq = (_seed * _seed) + ''; _seed = parseInt(sq.substring(0,4)); return parseFloat('0.' + _seed); } 
+2
source

If you do not like Math.Random, you can create your own Random .

import:

 import java.util.Random; 

code:

 Random rand = new Random(); int value = rand.nextInt(); 

If you need other types instead of int, Random will provide methods for boolean, double, float, long, byte.

+1
source

You can use java.security.SecureRandom . It has better entropy.

In addition, here is code from the book Data Structures and Algorithm Analysis in Java . It uses the same algorithm as java.util.Random.

0
source

I know that for poker websites they use things like CPU temperature, they don’t know what to use to get this, though

0
source

Source: https://habr.com/ru/post/1446799/


All Articles