How would you set up a program using Java to generate a 5 digit number using the following statement:
int n = (int)Math.floor(Math.random()*100000+1)
It also has to print the number generated. I have tried writing this different ways and keep coming up with errors.
There are two ways of looking at your problem. Either you need to make sure the random number generator only produces numbers with exactly five digits (in the range 10000 - 99999) or you need to print the numbers with leading 0s when a number is produced that's too low.
The first approach is best met using Java's Random class.
Random rand = new Random();
int n = rand.nextInt(90000) + 10000;
System.out.println(n);
If you're restricted in some way that you must use the statement in your question, then the second approach is probably what you're after. You can use Java's DecimalFormat class to format a random number with leading zeros before printing.
n = (int)Math.floor( Math.random() * 100000 + 1 );
NumberFormat formatter = new DecimalFormat("00000");
String number = formatter.format(n);
System.out.println("Number with lading zeros: " + number);
One might do:
public class Test {
public static void main(String[] args) {
int n = (int)Math.floor(Math.random()*100000+1);
System.out.println(n);
}
}
However, this really isn't the preferred way of generating random integers. Check out the Random class.
Random r = new Random();
for (;;) {
System.out.println(10000 + r.nextInt(90000));
}
A better idea is to generate the number by successively generating 5 random digits. Making the first digit non-zero ensures that the generated number is always 5-digit. I'm posting pseudocode below, it should be easy to convert it into Java code.
A = List(1,2,3,4,5,6,7,8,9)
B = List(0,1,2,3,4,5,6,7,8,9)
output = 0
output=random.choice(A) //first digit from A, no zeros
for i=0 to 4
output=output*10
output=output+random.choice(B) //next digits from B, can have zero
return output
Look up the API docs for Random if you are stuck.
A way to get a random number 00000 - 99999 is to use the following.
Random r= new Random();
// possibly too obtuse for most readers. ;)
System.out.println((""+(100000+r.nextInt(100000))).substring(1));
Related
I have to generate unique serial numbers for users consisting of 12 to 13 digits. I want to use random number generator in Java giving the system. Time in milliseconds as a seed to it. Please let me know about the best practice for doing so. What I did was like this
Random serialNo = new Random(System.currentTimeMillis());
System.out.println("serial number is "+serialNo);
Output came out as: serial number is java.util.Random#13d8cc98
For a bit better algorithm pick SecureRandom.
You passed a seed to the random constructor. This will pick a fixed sequence with that number. A hacker knowing the approximate time of calling, might restrict the number of attempts. So another measure is not using the constructor and nextLong at the same spot.
SecureRandom random = new SecureRandom​();
long n = random.nextLong();
A symmetric bit operation might help:
n ^= System.currentMillis();
However there is a unique number generation, the UUID, a unique 128 bits number, two longs. If you xor them (^) the number no longer is that unique, but might still be better having mentioned the circumstantial usage of random numbers.
UUID id = UUID.randomUUID();
long n = id.getLeastSignificantBits() ^ id.getMostSignificantBits();
Create a random number generator using the current time as seed (as you did)
long seed = System.currentTimeMillis();
Random rng = new Random​(seed);
Now, to get a number, you have to use the generator, rng is NOT a number.
long number = rng.nextLong();
According to the documentation, this will give you a pseudorandom number with 281.474.976.710.656 different possible values.
Now, to get a number with a maximum of 13 digits:
long number = rng.nextLong() % 10000000000000;
And to get a number with exactly 13 digits:
long number = (rng.nextLong() % 9000000000000) + 1000000000000;
First, import the Random class:
import java.util.Random;
Then create an instance of this class, with the current milliseconds as its seed:
Random rng = new Random(System.currentTimeMillis());
This line would generate an integer that can have up to 13 digits:
long result = rng.nextLong() % 10000000000000;
This line would generate an integer that always have 13 digits:
long result = rng.nextLong() % 9000000000000 + 1000000000000;
There are three ways to generate Random numbers in java
java.util.Random class
We can generate random numbers of types integers, float, double, long, booleans using this class.
Example :
//Random rand = new Random();
// rand_int1 = rand.nextInt(1000)
Math.random method : Can Generate Random Numbers of double type.
random(), this method returns a double value with a positive sign, greater than or equal to 0.0 and less than 1.0.
Example :
Math.random());
//Gives output 0.15089348615777683
ThreadLocalRandom class
This class is introduced in java 1.7 to generate random numbers of type integers, doubles, booleans etc
Example :
//int random_int1 = ThreadLocalRandom.current().nextInt();
// Print random integers
//System.out.println("Random Integers: " + random_int1);
In Java, I want to generate a program that generates a string of around 15 numbers based on a seed. It always needs to be from 1 to 9. It should seem random, but each seed spits out the same sequence.
For example if you type the number 5, it might output 194639573978476, but if you enter 6, it would output 657362047273958, and 5 will always output 194639573978476.
How do i do this?
First :If two instances of Random are created with the same seed, and the same sequence of method calls is made for each, they will generate and return identical sequences of numbers.
Source:Oracle
For this reason the seed needs to be different every time to generate a different numbers. You can use the time as seed. Like this,
Random random = new Random(System.currentTimeMillis());
StringBuffer sb = new StringBuffer();
for (int i = 0; i < 15; i++) {
sb.append(Integer.toString((random.nextInt(9) + 1)));
}
System.out.println(sb.toString());
Sample output every time you run the code:
146645139262732
919846574753947
662686147977574
Hope this helps!
First, create an instance of Random and give it your seed as an argument:
Random rand = new Random(seed);
Then just get 15 numbers. You can use a stringbuilder to build the string, or any other way you want. Shouldn't be too hard, but here's a quick and dirty way to do it:
String result = "";
for(int i = 0; i < 15; i++) {
result += rand.nextInt() % 9 + 1;
}
Please note this is some very dirty programming, did it this way for the sake of simplicity and readability. This is very poor style and you shouldn't copy paste this without changing it.
I am trying to generate random integers within a range to sample a percentile of that range. For example: for range 1 to 100 I would like to select a random sample of 20%. This would result in 20 integers randomly selected for 100.
This is to solve an extremely complex issue and I will post solutions once I get this and a few bugs worked out. I have not used many math packages in java so I appreciate your assistance.
Thanks!
Put all numbers in a arraylist, then shuffle it. Take only the 20 first element of the arraylist:
ArrayList<Integer> randomNumbers = new ArrayList<Integer>();
for(int i = 0; i < 100; i++){
randomNumbers.add((int)(Math.random() * 100 + 1));
}
Collections.shuffle(randomNumbers);
//Then the first 20 elements are your sample
If you want 20 random integers between 1 and one hundred, use Math.random() to generate a value between 0 and 0.999... Then, manipulate this value to fit your range.
int[] random = new int[20];
for(int i =0; i< random.length;i++)
{
random[i] = (int)(Math.random()*100+1);
}
When you multiply Math.random() by 100, you get a value between 0 and 99.999... To this number you add 1, yielding a value between 1.0 and 100.0. Then, I typecasted the number to an integer by using the (int) typecast. This gives a number between 1 and 100 inclusive. Then, store the values into an array.
If you are willing to go with Java 8, you could use some features of lambdas. Presuming that you aren't keeping 20% of petabytes of data, you could do something like this (number is the number of integers in the range to get) it isn't efficient in the slightest, but it works, and is fun if you'd like to do some Java 8. But if this is performance critical, I wouldn't recommend it:
public ArrayList<Integer> sampler(int min, int max, int number){
Random random = new Random();
ArrayList<Integer> generated = new ArrayList<Integer>();
IntStream ints = random.ints(min,max);
Iterator<Integer> it = ints.iterator();
for(int i = 0; i < number; i++){
int k = it.next();
while(generated.contains(k)){
k = it.next();
}
generated.add(k);
}
ints.close();
return generated;
}
If you really need to scale to petabytes of data, you're going to need a solution that doesn't require keeping all your numbers in memory. Even a bit-set, which would compress your numbers to 1 byte per 8 integers, wouldn't fit in memory.
Since you didn't mention the numbers had to be shuffled (just random), you can start counting and randomly decide whether to keep each number or not. Then stream your result to a file or wherever you need it.
Start with this:
long range = 100;
float percentile = 0.20f;
Random rnd = new Random();
for (long i=1; i < range; i++) {
if (rnd.nextFloat() < percentile) {
System.out.println(i);
}
}
You will get about 20 percent of the numbers from 1 to 100, with no duplicates.
As the range goes up, the accuracy will too, so you really wouldn't need any special logic for large data sets.
If an exact number is needed, you would need special logic for smaller data sets, but that's pretty easy to solve using other methods posted here (although I'd still recommend a bit set).
I am randomly generating numbers using java.util.Random. But, I can not keep the length of the numbers fixed. Can you help me please?
To fix the length of a randomly generated number, generally you'll want to fix the random number generation to a range. For instance, if you'd like to generate a 6 digit long random number, you'll want numbers from 100,000 to 999,999. You can achieve this by using the following formula.
Random r = new Random();
int randomNum = r.nextInt((max - min) + 1) + min;
Where max is the maximum number, such as 999999, and min is your minimum number, such as 100000.
EDIT:
Based on your comment, I see that you're trying to generate a 15-digit number containing only 1-5 inclusive. Here is a simple way to do this:
import java.util.Random;
StringBuilder s = new StringBuilder();
Random r = new Random();
for (int i = 0; i < 15; i++) {
s.append(r.nextInt(5) + 1);
}
System.out.println("The random number is: " + s.toString());
As noted by #MichaelT, a 15 digit number will not fit in an integer. If you need to perform an operation on it, you should store it in a long.
long randomLong = Long.valueOf(s.toString()).longValue();
Rather than thinking of generating an integer, think in terms of generating a String of 15 digits, each in the required range.
You can use nextInt(int) to pick each digit.
The first thing to consider is that an int cannot hold 15 digits. It just can't. It can only go up to 232 -1, which is 9 digits long. A long can hold up to 19 digits - but if one wants to solve for the general case, it is necessary to use the BigInteger package instead.
Remember that BigInteger is an immutable object (like String) and thus you must assign the value back when looping.
package com.michaelt.so.random15;
import java.math.BigInteger;
import java.util.Random;
public class Main {
public static void main(String[] args) {
Random r = new Random();
BigInteger result = BigInteger.ZERO;
for(int i = 0; i < 15; i++) {
result = result.multiply(BigInteger.TEN)
.add(BigInteger.valueOf(r.nextInt(5)+1));
}
System.out.println(result.toString());
}
}
It starts out with the value ZERO, and loops through for 15 times, each time first multiplying the value by 10 (another BigInteger preallocated value) and then adds the new value into the 1's position. It does this 15 times.
When done, one can get its value as a string or long or other format - or continue to use it as a BigDecimal (necessary if you should ever decide you want a 20 digit long value).
Runs of the above code produce output such as:
313455131111333
245114532433152
531153533113523
If you're ok using libraries:
RandomStringUtils.random(15, "12345")
would give you Strings like: 124444211351355 of length 15
I just happened to write a post about that (shameless self-advertising link: http://united-coders.com/nico-heid/generating-random-numbers-strings-java/)
This is my homework assignment:
Random r = new Random();
public int get100RandomNumber() {
return 1 + r.nextInt(100);
}
You are given a pre-defined function named getrand100() (above) which
returns an integer which is one random number from 1-100. You can call
this function as many times as you want but beware that this function
is quite resource intensive. You cannot use any other random
generator. You cannot change the definition of getrand100().
Output: Print numbers 1-20 in random order. (Not 20 random numbers)
What I have tried..
public class MyClass {
static Random r = new Random();
static HashSet<Integer>;
public static void main(String args[]) {
myMethod();
System.out.println(s);
}
public static void myMethod() {
boolean b = false;
s = new HashSet<Integer>();
int i = getRand100();
if (i >= 20)
i = i % 20;
int j = 0;
int k, l;
while (s.size() <= 20)
{
System.out.println("occurence no" + ++j);
System.out.println("occurence value" + i);
b = s.add(i);
while (!b) {
k = ++i;
if(k<=20)
b = s.add(k);
if(b==true)
break;
if (!b) {
l = --i;
if(i>=1&&i<=20)
b = s.add(l);
if(b==true)
break;
}
}
}
System.out.println(s);
}
public static int getRand100()
{
return r.nextInt(100) + 1;
}
}
Thanks for any help!
I believe you are asking how to use a random number generator to print out the numbers 1 to 20 in a random order. This is also known as a "random permutation". The Fischer-Yates shuffle is such an algorithm.
However, to implement the algorithm, you first of all need a random number generator that can pick one out of N items with equal probability where N ranges from 2 up to the size of the set to shuffle, while you only have one that can pick one out of 100 items with equal probability. That can easily be obtained by a combination of modulo arithmetic and "rerolling".
Assuming you are allowed to use the ArrayList class, I'd recommend filling a list with the numbers you want (1 to 20 in this case), then randomly pick numbers from the list and remove them. Using getRand100() % theList.size() should be sufficiently random for your cause and you only need to call it 19 times. When only one element is left, there's no need to "randomly" pick it from the list anymore. ;-)
I believe that I've come up with a way to convert any number between 1 and n! (assuming the number of items is known) to a unique permutation of n items.
In essence, this allows for an "immediate" randomization of an entire deck without having to use any shuffling algorithms. For now, it runs in O(n^2) and requires using BigInteger packages (ie. in Java or Javascript), but I'm looking for ways to optimize the runtime (although, honestly 2500 iterations is nothing these days anyway). Regardless, when given at least 226 bits of valid, random data, the function is able to generate a shuffled array of 52 integers in under 10 ms.
The method is similar to that used to convert a decimal number to binary (continually dividing by 2, etc). I'm happy to provide my code upon request; I find it interesting that I haven't come across it before.