Java/Development Class/Random
Версия от 18:01, 31 мая 2010; (обсуждение)
Содержание
- 1 A wrapper that supports all possible Random methods via the java.lang.Math#random() method and its system-wide {@link Random} object.
- 2 Create random number
- 3 Create two random number generators with the same seed
- 4 Does Math.random() produce 0.0 and 1.0
- 5 Generate a random array of numbers
- 6 Generate random ints by asking Random() for
- 7 Generating random numbers
- 8 Getting random numbers: nextGaussian
- 9 Math.random
- 10 nextDouble() and nextGaussian() in java.util.Random
- 11 Next double and next int
- 12 Operations for random Strings
- 13 Random boolean
- 14 Random bytes
- 15 Random double type number
- 16 Random float type number
- 17 Random integers that range from from 0 to n
- 18 Randomizer
- 19 Random long type number
- 20 Random.nextInt(n) returns a distributed int value between 0 (inclusive) and n (exclusive).
- 21 Random number between 0 AND 10
- 22 Random numbers between 1 and 100
- 23 Round Java float and double numbers using Math.round
A wrapper that supports all possible Random methods via the java.lang.Math#random() method and its system-wide {@link Random} object.
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
import java.util.Random;
/**
* <p><code>JVMRandom</code> is a wrapper that supports all possible
* Random methods via the {@link java.lang.Math#random()} method
* and its system-wide {@link Random} object.</p>
*
* @since 2.0
* @version $Id: JVMRandom.java 471626 2006-11-06 04:02:09Z bayard $
*/
public final class JVMRandom extends Random {
/**
* Required for serialization support.
*
* @see java.io.Serializable
*/
private static final long serialVersionUID = 1L;
/**
* Ensures that only the constructor can call reseed.
*/
private boolean constructed = false;
/**
* Constructs a new instance.
*/
public JVMRandom() {
this.constructed = true;
}
/**
* Unsupported in 2.0.
*
* @param seed ignored
* @throws UnsupportedOperationException
*/
public synchronized void setSeed(long seed) {
if (this.constructed) {
throw new UnsupportedOperationException();
}
}
/**
* Unsupported in 2.0.
*
* @return Nothing, this method always throws an UnsupportedOperationException.
* @throws UnsupportedOperationException
*/
public synchronized double nextGaussian() {
throw new UnsupportedOperationException();
}
/**
* Unsupported in 2.0.
*
* @param byteArray ignored
* @throws UnsupportedOperationException
*/
public void nextBytes(byte[] byteArray) {
throw new UnsupportedOperationException();
}
/**
* <p>Returns the next pseudorandom, uniformly distributed int value
* from the Math.random() sequence.</p>
*
* @return the random int
*/
public int nextInt() {
return nextInt(Integer.MAX_VALUE);
}
/**
* <p>Returns a pseudorandom, uniformly distributed int value between
* <code>0</code> (inclusive) and the specified value (exclusive), from
* the Math.random() sequence.</p>
*
* @param n the specified exclusive max-value
* @return the random int
* @throws IllegalArgumentException when <code>n <= 0</code>
*/
public int nextInt(int n) {
if (n <= 0) {
throw new IllegalArgumentException(
"Upper bound for nextInt must be positive"
);
}
// TODO: check this cannot return "n"
return (int)(Math.random() * n);
}
/**
* <p>Returns the next pseudorandom, uniformly distributed long value
* from the Math.random() sequence.</p>
* @return the random long
*/
public long nextLong() {
// possible loss of precision?
return nextLong(Long.MAX_VALUE);
}
/**
* <p>Returns a pseudorandom, uniformly distributed long value between
* <code>0</code> (inclusive) and the specified value (exclusive), from
* the Math.random() sequence.</p>
*
* @param n the specified exclusive max-value
* @return the random long
* @throws IllegalArgumentException when <code>n <= 0</code>
*/
public static long nextLong(long n) {
if (n <= 0) {
throw new IllegalArgumentException(
"Upper bound for nextInt must be positive"
);
}
// TODO: check this cannot return "n"
return (long)(Math.random() * n);
}
/**
* <p>Returns the next pseudorandom, uniformly distributed boolean value
* from the Math.random() sequence.</p>
*
* @return the random boolean
*/
public boolean nextBoolean() {
return Math.random() > 0.5;
}
/**
* <p>Returns the next pseudorandom, uniformly distributed float value
* between <code>0.0</code> and <code>1.0</code> from the Math.random()
* sequence.</p>
*
* @return the random float
*/
public float nextFloat() {
return (float)Math.random();
}
/**
* <p>Synonymous to the Math.random() call.</p>
*
* @return the random double
*/
public double nextDouble() {
return Math.random();
}
}
Create random number
public class Main {
public static void main(String[] args) {
double number = Math.random();
System.out.println("Generated number: " + number);
number = Math.random() * 10;
System.out.println("Generated number: " + number);
number = 100 + (Math.random() * 100);
System.out.println("Generated number: " + number);
int random = 100 + (int) (Math.random() * 100);
System.out.println("Generated number: " + random);
}
}
Create two random number generators with the same seed
import java.util.Random;
public class Main {
public static void main(String[] argv) throws Exception {
Random rand = new Random();
long seed = rand.nextLong();
rand = new Random(seed);
Random rand2 = new Random(seed);
}
}
Does Math.random() produce 0.0 and 1.0
//: c03:RandomBounds.java
// Does Math.random() produce 0.0 and 1.0?
// {RunByHand}
// From "Thinking in Java, 3rd ed." (c) Bruce Eckel 2002
// www.BruceEckel.ru. See copyright notice in CopyRight.txt.
public class RandomBounds {
static void usage() {
System.out.println("Usage: \n\t" +
"RandomBounds lower\n\tRandomBounds upper");
System.exit(1);
}
public static void main(String[] args) {
if(args.length != 1) usage();
if(args[0].equals("lower")) {
while(Math.random() != 0.0)
; // Keep trying
System.out.println("Produced 0.0!");
}
else if(args[0].equals("upper")) {
while(Math.random() != 1.0)
; // Keep trying
System.out.println("Produced 1.0!");
}
else
usage();
}
} ///:~
Generate a random array of numbers
import java.util.Random;
public class Main {
public static void main(String[] args) {
Random r = new Random();
// generate some random boolean values
boolean[] booleans = new boolean[10];
for (int i = 0; i < booleans.length; i++) {
booleans[i] = r.nextBoolean();
}
for (boolean b : booleans) {
System.out.print(b + ", ");
}
// generate a uniformly distributed int random numbers
int[] integers = new int[10];
for (int i = 0; i < integers.length; i++) {
integers[i] = r.nextInt();
}
for (int i : integers) {
System.out.print(i + ", ");
}
// generate a uniformly distributed float random numbers
float[] floats = new float[10];
for (int i = 0; i < floats.length; i++) {
floats[i] = r.nextFloat();
}
for (float f : floats) {
System.out.print(f + ", ");
}
// generate a Gaussian normally distributed random numbers
double[] gaussians = new double[10];
for (int i = 0; i < gaussians.length; i++) {
gaussians[i] = r.nextGaussian();
}
for (double d : gaussians) {
System.out.print(d + ", ");
}
}
}
Generate random ints by asking Random() for
import java.util.*;
/** Generate random ints by asking Random() for
* a series of random integers from 1 to 10, inclusive.
*
* @author Ian Darwin, http://www.darwinsys.ru/
* @version $Id: RandomInt.java,v 1.4 2004/03/07 02:51:50 ian Exp $
*/
public class RandomInt {
public static void main(String[] a) {
Random r = new Random();
for (int i=0; i<1000; i++)
// nextInt(10) goes from 0-9; add 1 for 1-10;
System.out.println(1+Math.round(r.nextInt(10)));
}
}
Generating random numbers
/*
Java Programming for Engineers
Julio Sanchez
Maria P. Canton
ISBN: 0849308100
Publisher: CRC Press
*/
// Java for Engineers
//Filename: RandNum
//Reference: Chapter 23
//Description:
// Generating random numbers
class RandNum {
public static void main(String[] args) {
int num;
int[] dist = new int[10]; // Storage for distribution
// Generate 10000 random numbers using Math.random()
for (int x = 0; x < 10000; x++) {
num = (int) (Math.floor(Math.random() * 10));
dist[num]++;
}
// Display distribution of random integers in the range
// 0 to 9
System.out.println("Distribution using Math.random() ");
for (int k = 0; k < 10; k++)
System.out.print(k + "\t");
// Display results
for (int y = 0; y < 10; y++) {
System.out.print(dist[y] + "\t");
}
System.out.println();
}
}
Getting random numbers: nextGaussian
import java.util.*;
/** Demonstrate the better way of getting random numbers,
* using java.util.Random.next*().
*/
public class Random3 {
public static void main(String[] argv) {
// java.util.Random methods are non-static, do need to construct Math
//+
Random r = new Random();
for (int i=0; i<10; i++)
System.out.println("A gaussian random double is " + r.nextGaussian());
//-
}
}
Math.random
/** Demonstrate the easy way of getting random numbers,
* using java.lang.Math.Random().
*/
public class Random1 {
public static void main(String[] argv) {
//+
// java.lang.Math.random() is static, don"t need to construct Math
System.out.println("A random from java.lang.Math is " + Math.random());
//-
}
}
nextDouble() and nextGaussian() in java.util.Random
import java.util.*;
import java.io.*;
/** Print "n" calls to nextDouble() and nextGaussian() in raw form
* using java.util.Random.next*(); results can be plotted.
*/
public class Random4 {
public static void main(String[] argv) throws IOException {
// java.util.Random methods are non-static, do need to construct Math
Random r = new Random();
PrintWriter file1 = new PrintWriter(new FileWriter("file1"));
PrintWriter file2 = new PrintWriter(new FileWriter("file2"));
for (int i=0; i<10000; i++) {
file1.println(r.nextDouble());
file2.println(r.nextGaussian());
}
file1.close();
file2.close();
}
}
Next double and next int
import java.util.*;
/** Demonstrate the better way of getting random numbers,
* using java.util.Random.next*().
*/
public class Random2 {
public static void main(String[] argv) {
//+
// java.util.Random methods are non-static, so need to construct
Random r = new Random();
for (int i=0; i<10; i++)
System.out.println("A double from java.util.Random is " + r.nextDouble());
for (int i=0; i<10; i++)
System.out.println("An integer from java.util.Random is " + r.nextInt());
//-
}
}
Operations for random Strings
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import java.util.Random;
/**
* <p>Operations for random <code>String</code>s.</p>
* <p>Currently <em>private high surrogate</em> characters are ignored.
* These are unicode characters that fall between the values 56192 (db80)
* and 56319 (dbff) as we don"t know how to handle them.
* High and low surrogates are correctly dealt with - that is if a
* high surrogate is randomly chosen, 55296 (d800) to 56191 (db7f)
* then it is followed by a low surrogate. If a low surrogate is chosen,
* 56320 (dc00) to 57343 (dfff) then it is placed after a randomly
* chosen high surrogate. </p>
*
* @author
* @author Stephen Colebourne
* @author Gary Gregory
* @author Phil Steitz
* @since 1.0
* @version $Id: RandomStringUtils.java 471626 2006-11-06 04:02:09Z bayard $
*/
public class RandomStringUtils {
/**
* <p>Random object used by random method. This has to be not local
* to the random method so as to not return the same value in the
* same millisecond.</p>
*/
private static final Random RANDOM = new Random();
/**
* <p><code>RandomStringUtils</code> instances should NOT be constructed in
* standard programming. Instead, the class should be used as
* <code>RandomStringUtils.random(5);</code>.</p>
*
* <p>This constructor is public to permit tools that require a JavaBean instance
* to operate.</p>
*/
public RandomStringUtils() {
super();
}
// Random
//-----------------------------------------------------------------------
/**
* <p>Creates a random string whose length is the number of characters
* specified.</p>
*
* <p>Characters will be chosen from the set of all characters.</p>
*
* @param count the length of random string to create
* @return the random string
*/
public static String random(int count) {
return random(count, false, false);
}
/**
* <p>Creates a random string whose length is the number of characters
* specified.</p>
*
* <p>Characters will be chosen from the set of characters whose
* ASCII value is between <code>32</code> and <code>126</code> (inclusive).</p>
*
* @param count the length of random string to create
* @return the random string
*/
public static String randomAscii(int count) {
return random(count, 32, 127, false, false);
}
/**
* <p>Creates a random string whose length is the number of characters
* specified.</p>
*
* <p>Characters will be chosen from the set of alphabetic
* characters.</p>
*
* @param count the length of random string to create
* @return the random string
*/
public static String randomAlphabetic(int count) {
return random(count, true, false);
}
/**
* <p>Creates a random string whose length is the number of characters
* specified.</p>
*
* <p>Characters will be chosen from the set of alpha-numeric
* characters.</p>
*
* @param count the length of random string to create
* @return the random string
*/
public static String randomAlphanumeric(int count) {
return random(count, true, true);
}
/**
* <p>Creates a random string whose length is the number of characters
* specified.</p>
*
* <p>Characters will be chosen from the set of numeric
* characters.</p>
*
* @param count the length of random string to create
* @return the random string
*/
public static String randomNumeric(int count) {
return random(count, false, true);
}
/**
* <p>Creates a random string whose length is the number of characters
* specified.</p>
*
* <p>Characters will be chosen from the set of alpha-numeric
* characters as indicated by the arguments.</p>
*
* @param count the length of random string to create
* @param letters if <code>true</code>, generated string will include
* alphabetic characters
* @param numbers if <code>true</code>, generated string will include
* numeric characters
* @return the random string
*/
public static String random(int count, boolean letters, boolean numbers) {
return random(count, 0, 0, letters, numbers);
}
/**
* <p>Creates a random string whose length is the number of characters
* specified.</p>
*
* <p>Characters will be chosen from the set of alpha-numeric
* characters as indicated by the arguments.</p>
*
* @param count the length of random string to create
* @param start the position in set of chars to start at
* @param end the position in set of chars to end before
* @param letters if <code>true</code>, generated string will include
* alphabetic characters
* @param numbers if <code>true</code>, generated string will include
* numeric characters
* @return the random string
*/
public static String random(int count, int start, int end, boolean letters, boolean numbers) {
return random(count, start, end, letters, numbers, null, RANDOM);
}
/**
* <p>Creates a random string based on a variety of options, using
* default source of randomness.</p>
*
* <p>This method has exactly the same semantics as
* {@link #random(int,int,int,boolean,boolean,char[],Random)}, but
* instead of using an externally supplied source of randomness, it uses
* the internal static {@link Random} instance.</p>
*
* @param count the length of random string to create
* @param start the position in set of chars to start at
* @param end the position in set of chars to end before
* @param letters only allow letters?
* @param numbers only allow numbers?
* @param chars the set of chars to choose randoms from.
* If <code>null</code>, then it will use the set of all chars.
* @return the random string
* @throws ArrayIndexOutOfBoundsException if there are not
* <code>(end - start) + 1</code> characters in the set array.
*/
public static String random(int count, int start, int end, boolean letters, boolean numbers, char[] chars) {
return random(count, start, end, letters, numbers, chars, RANDOM);
}
/**
* <p>Creates a random string based on a variety of options, using
* supplied source of randomness.</p>
*
* <p>If start and end are both <code>0</code>, start and end are set
* to <code>" "</code> and <code>"z"</code>, the ASCII printable
* characters, will be used, unless letters and numbers are both
* <code>false</code>, in which case, start and end are set to
* <code>0</code> and <code>Integer.MAX_VALUE</code>.
*
* <p>If set is not <code>null</code>, characters between start and
* end are chosen.</p>
*
* <p>This method accepts a user-supplied {@link Random}
* instance to use as a source of randomness. By seeding a single
* {@link Random} instance with a fixed seed and using it for each call,
* the same random sequence of strings can be generated repeatedly
* and predictably.</p>
*
* @param count the length of random string to create
* @param start the position in set of chars to start at
* @param end the position in set of chars to end before
* @param letters only allow letters?
* @param numbers only allow numbers?
* @param chars the set of chars to choose randoms from.
* If <code>null</code>, then it will use the set of all chars.
* @param random a source of randomness.
* @return the random string
* @throws ArrayIndexOutOfBoundsException if there are not
* <code>(end - start) + 1</code> characters in the set array.
* @throws IllegalArgumentException if <code>count</code> < 0.
* @since 2.0
*/
public static String random(int count, int start, int end, boolean letters, boolean numbers,
char[] chars, Random random) {
if (count == 0) {
return "";
} else if (count < 0) {
throw new IllegalArgumentException("Requested random string length " + count + " is less than 0.");
}
if ((start == 0) && (end == 0)) {
end = "z" + 1;
start = " ";
if (!letters && !numbers) {
start = 0;
end = Integer.MAX_VALUE;
}
}
char[] buffer = new char[count];
int gap = end - start;
while (count-- != 0) {
char ch;
if (chars == null) {
ch = (char) (random.nextInt(gap) + start);
} else {
ch = chars[random.nextInt(gap) + start];
}
if ((letters && Character.isLetter(ch))
|| (numbers && Character.isDigit(ch))
|| (!letters && !numbers))
{
if(ch >= 56320 && ch <= 57343) {
if(count == 0) {
count++;
} else {
// low surrogate, insert high surrogate after putting it in
buffer[count] = ch;
count--;
buffer[count] = (char) (55296 + random.nextInt(128));
}
} else if(ch >= 55296 && ch <= 56191) {
if(count == 0) {
count++;
} else {
// high surrogate, insert low surrogate before putting it in
buffer[count] = (char) (56320 + random.nextInt(128));
count--;
buffer[count] = ch;
}
} else if(ch >= 56192 && ch <= 56319) {
// private high surrogate, no effing clue, so skip it
count++;
} else {
buffer[count] = ch;
}
} else {
count++;
}
}
return new String(buffer);
}
/**
* <p>Creates a random string whose length is the number of characters
* specified.</p>
*
* <p>Characters will be chosen from the set of characters
* specified.</p>
*
* @param count the length of random string to create
* @param chars the String containing the set of characters to use,
* may be null
* @return the random string
* @throws IllegalArgumentException if <code>count</code> < 0.
*/
public static String random(int count, String chars) {
if (chars == null) {
return random(count, 0, 0, false, false, null, RANDOM);
}
return random(count, chars.toCharArray());
}
/**
* <p>Creates a random string whose length is the number of characters
* specified.</p>
*
* <p>Characters will be chosen from the set of characters specified.</p>
*
* @param count the length of random string to create
* @param chars the character array containing the set of characters to use,
* may be null
* @return the random string
* @throws IllegalArgumentException if <code>count</code> < 0.
*/
public static String random(int count, char[] chars) {
if (chars == null) {
return random(count, 0, 0, false, false, null, RANDOM);
}
return random(count, 0, chars.length, false, false, chars, RANDOM);
}
}
Random boolean
import java.util.Random;
public class Main {
public static void main(String[] argv) throws Exception {
Random rand = new Random();
boolean b = rand.nextBoolean();
long l = rand.nextLong();
float f = rand.nextFloat(); // 0.0 <= f < 1.0
double d = rand.nextDouble(); // 0.0 <= d < 1.0
}
}
Random bytes
import java.util.Random;
public class Main {
public static void main(String[] argv) throws Exception {
Random rand = new Random();
byte[] bytes = new byte[5];
rand.nextBytes(bytes);
}
}
Random double type number
import java.util.Random;
public class Main {
public static void main(String[] argv) throws Exception {
Random rand = new Random();
boolean b = rand.nextBoolean();
long l = rand.nextLong();
float f = rand.nextFloat(); // 0.0 <= f < 1.0
double d = rand.nextDouble(); // 0.0 <= d < 1.0
}
}
Random float type number
import java.util.Random;
public class Main {
public static void main(String[] argv) throws Exception {
Random rand = new Random();
boolean b = rand.nextBoolean();
long l = rand.nextLong();
float f = rand.nextFloat(); // 0.0 <= f < 1.0
double d = rand.nextDouble(); // 0.0 <= d < 1.0
}
}
Random integers that range from from 0 to n
import java.util.Random;
public class Main {
public static void main(String[] argv) throws Exception {
Random rand = new Random();
int n = 10;
int i = rand.nextInt(n + 1);
System.out.println(i);
}
}
Randomizer
/*
* Copyright (c) 2000 David Flanagan. All rights reserved.
* This code is from the book Java Examples in a Nutshell, 2nd Edition.
* It is provided AS-IS, WITHOUT ANY WARRANTY either expressed or implied.
* You may study, use, and modify it for any non-commercial purpose.
* You may distribute it non-commercially as long as you retain this notice.
* For a commercial use license, or to purchase the book (recommended),
* visit http://www.davidflanagan.ru/javaexamples2.
*/
/**
* This class defines methods for computing pseudo-random numbers, and defines
* the state variable that needs to be maintained for use by those methods.
*/
public class Randomizer {
// Carefully chosen constants from the book "Numerical Recipes in C".
// All "static final" fields are constants.
static final int m = 233280;
static final int a = 9301;
static final int c = 49297;
// The state variable maintained by each Randomizer instance
int seed = 1;
/**
* The constructor for the Randomizer() class. It must be passed some
* arbitrary initial value or "seed" for its pseudo-randomness.
*/
public Randomizer(int seed) {
this.seed = seed;
}
/**
* This method computes a pseudo-random number between 0 and 1 using a very
* simple algorithm. Math.random() and java.util.Random are actually a lot
* better at computing randomness.
*/
public float randomFloat() {
seed = (seed * a + c) % m;
return (float) Math.abs((float) seed / (float) m);
}
/**
* This method computes a pseudo-random integer between 0 and specified
* maximum. It uses randomFloat() above.
*/
public int randomInt(int max) {
return Math.round(max * randomFloat());
}
/**
* This nested class is a simple test program: it prints 10 random ints.
* Note how the Randomizer object is seeded using the current time.
*/
public static void main(String[] args) {
Randomizer r = new Randomizer((int) new java.util.Date().getTime());
for (int i = 0; i < 10; i++)
System.out.println(r.randomInt(100));
}
}
Random long type number
import java.util.Random;
public class Main {
public static void main(String[] argv) throws Exception {
Random rand = new Random();
boolean b = rand.nextBoolean();
long l = rand.nextLong();
float f = rand.nextFloat(); // 0.0 <= f < 1.0
double d = rand.nextDouble(); // 0.0 <= d < 1.0
}
}
Random.nextInt(n) returns a distributed int value between 0 (inclusive) and n (exclusive).
// random number between 0 AND 10
import java.util.Random;
public class Main {
public static void main(String[] argv) {
Random r = new Random();
int randint = r.nextInt(10);
System.out.println(randint);
}
}
Random number between 0 AND 10
import java.util.Random;
public class Main {
public static void main(String[] argv) {
Random r = new Random();
int randint = Math.abs(r.nextInt()) % 11;
System.out.println(randint);
}
}
Random numbers between 1 and 100
public class Main {
public static void main(String[] args) {
for(int i=0; i < 5 ; i++){
System.out.println("Random Number ["+ (i+1) + "] : " + (int)(Math.random()*100));
}
}
}
Round Java float and double numbers using Math.round
public class Main {
public static void main(String[] args) {
System.out.println(Math.round(10f));
System.out.println(Math.round(2.5f));
System.out.println(Math.round(-1.4f));
System.out.println(Math.round(-2.5f));
}
}
/*
10
3
-1
-2
*/