Java Tutorial/Development/Random
Содержание
- 1 Create two random number generators with the same seed
- 2 Generate a random array of numbers
- 3 Generating Random integer Numbers
- 4 Operations for random Strings
- 5 Random boolean
- 6 Random bytes
- 7 Random double type number
- 8 Random float type number
- 9 Random Gaussian values.
- 10 Random integers that range from from 0 to n
- 11 Random long type number
- 12 Random.nextInt(n) returns a distributed int value between 0 (inclusive) and n (exclusive).
- 13 Random number between 0 AND 10
- 14 Random numbers between 0.0 and 1.0
- 15 Roll a six-sided die imes
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);
}
}
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 + ", ");
}
}
}
Generating Random integer Numbers
import java.util.Random;
public class MainClass {
public static void main(String[] args) {
Random diceValues = new Random();
System.out.println(diceValues.nextInt(6));
System.out.println(diceValues.nextInt(6));
}
}
5 3
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;
/**
* Operations for random <code>String</code>s.
* 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.
*
* @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 {
/**
* 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.
*/
private static final Random RANDOM = new Random();
/**
* <code>RandomStringUtils</code> instances should NOT be constructed in
* standard programming. Instead, the class should be used as
* <code>RandomStringUtils.random(5);</code>.
*
* This constructor is public to permit tools that require a JavaBean instance
* to operate.
*/
public RandomStringUtils() {
super();
}
// Random
//-----------------------------------------------------------------------
/**
* Creates a random string whose length is the number of characters
* specified.
*
* Characters will be chosen from the set of all characters.
*
* @param count the length of random string to create
* @return the random string
*/
public static String random(int count) {
return random(count, false, false);
}
/**
* Creates a random string whose length is the number of characters
* specified.
*
* Characters will be chosen from the set of characters whose
* ASCII value is between <code>32</code> and <code>126</code> (inclusive).
*
* @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);
}
/**
* Creates a random string whose length is the number of characters
* specified.
*
* Characters will be chosen from the set of alphabetic
* characters.
*
* @param count the length of random string to create
* @return the random string
*/
public static String randomAlphabetic(int count) {
return random(count, true, false);
}
/**
* Creates a random string whose length is the number of characters
* specified.
*
* Characters will be chosen from the set of alpha-numeric
* characters.
*
* @param count the length of random string to create
* @return the random string
*/
public static String randomAlphanumeric(int count) {
return random(count, true, true);
}
/**
* Creates a random string whose length is the number of characters
* specified.
*
* Characters will be chosen from the set of numeric
* characters.
*
* @param count the length of random string to create
* @return the random string
*/
public static String randomNumeric(int count) {
return random(count, false, true);
}
/**
* Creates a random string whose length is the number of characters
* specified.
*
* Characters will be chosen from the set of alpha-numeric
* characters as indicated by the arguments.
*
* @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);
}
/**
* Creates a random string whose length is the number of characters
* specified.
*
* Characters will be chosen from the set of alpha-numeric
* characters as indicated by the arguments.
*
* @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);
}
/**
* Creates a random string based on a variety of options, using
* default source of randomness.
*
* 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.
*
* @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);
}
/**
* Creates a random string based on a variety of options, using
* supplied source of randomness.
*
* 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>.
*
* If set is not <code>null</code>, characters between start and
* end are chosen.
*
* 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.
*
* @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);
}
/**
* Creates a random string whose length is the number of characters
* specified.
*
* Characters will be chosen from the set of characters
* specified.
*
* @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());
}
/**
* Creates a random string whose length is the number of characters
* specified.
*
* Characters will be chosen from the set of characters specified.
*
* @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 Gaussian values.
import java.util.Random;
class RandDemo {
public static void main(String args[]) {
Random r = new Random();
double val;
double sum = 0;
int bell[] = new int[10];
for (int i = 0; i < 100; i++) {
val = r.nextGaussian();
sum += val;
double t = -2;
for (int x = 0; x < 10; x++, t += 0.5)
if (val < t) {
bell[x]++;
break;
}
}
System.out.println("Average of values: " + (sum / 100));
for (int i = 0; i < 10; i++) {
for (int x = bell[i]; x > 0; x--)
System.out.print("*");
System.out.println();
}
}
}
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);
}
}
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 0.0 and 1.0
public class Main {
public static void main(String[] args) {
for (int i = 0; i < 5; i++){
System.out.println("Random Number [" + (i + 1) + "] : " + Math.random());
}
}
}
Roll a six-sided die imes
import java.util.Random;
public class MainClass
{
public static void main( String args[] )
{
Random randomNumbers = new Random(); // random number generator
int frequency1 = 0; // count of 1s rolled
int frequency2 = 0; // count of 2s rolled
int frequency3 = 0; // count of 3s rolled
int frequency4 = 0; // count of 4s rolled
int frequency5 = 0; // count of 5s rolled
int frequency6 = 0; // count of 6s rolled
int face; // stores most recently rolled value
// summarize results of 6000 rolls of a die
for ( int roll = 1; roll <= 6000; roll++ )
{
face = 1 + randomNumbers.nextInt( 6 ); // number from 1 to 6
// determine roll value 1-6 and increment appropriate counter
switch ( face )
{
case 1:
++frequency1; // increment the 1s counter
break;
case 2:
++frequency2; // increment the 2s counter
break;
case 3:
++frequency3; // increment the 3s counter
break;
case 4:
++frequency4; // increment the 4s counter
break;
case 5:
++frequency5; // increment the 5s counter
break;
case 6:
++frequency6; // increment the 6s counter
break; // optional at end of switch
}
}
System.out.println( "Face\tFrequency" ); // output headers
System.out.printf( "1\t%d\n2\t%d\n3\t%d\n4\t%d\n5\t%d\n6\t%d\n",
frequency1, frequency2, frequency3, frequency4,
frequency5, frequency6 );
}
}
Face Frequency 1 1005 2 1028 3 1027 4 989 5 994 6 957