10

My project entails that I create a basic number guessing game that uses the JOptionPane and does not use Math.Random to create the random value. How would you go about doing this? I've completed everything except the random number generator. Thanks!

jTC
  • 1,340
  • 9
  • 17
John Smith
  • 233
  • 2
  • 3
  • 7

4 Answers4

15

Here the code for 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 congruential generator (LCG)", you can find a good description of how it works here.

Disclamer:

The code above is designed to be used for research only, and not as a replacement to the stock Random or SecureRandom.

Frank
  • 16,476
  • 7
  • 38
  • 51
  • What are the magic numbers in there? 32719, 3 and 32749 ? I'm just trying to work out how the logic is working - which quite obviously it is. :-) – Penelope The Duck Nov 18 '12 at 20:40
  • Just 2 "large" prime numbers, i need to increase my last value all the time but keep it within some limits. note also that this prime number generator will fail if you ask for numbers bigger then 32749, but i don't think that the OP wishes to go that big. – Frank Nov 18 '12 at 20:46
5

In JavaScript using 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);
}
Blackwood
  • 4,504
  • 16
  • 32
  • 41
1

If you don't like the Math.Random you can make your own Random object.

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.

Frank
  • 16,476
  • 7
  • 38
  • 51
  • That would be fine normally but my professor is asking us to not use any given java methods. He wanted us to create our own random number generator that one could limit the range to a specified value. Thanks though! – John Smith Nov 18 '12 at 19:56
1

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

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

mikeslattery
  • 4,039
  • 1
  • 19
  • 14