Generate 6 digit random number [duplicate] - java

This question already has answers here:
How do I generate random integers within a specific range in Java?
(72 answers)
Closed 4 years ago.
I just want to generate 6 digit random number, and the range should be start from 000000 to 999999.
new Random().nextInt(999999) is returning me number but it is not in 6 digit.

Its as simple as that, you can use your code and just do one thing extra here
String.format("%06d", number);
this will return your number in string format, so the "0" will be "000000".
Here is the code.
public static String getRandomNumberString() {
// It will generate 6 digit random Number.
// from 0 to 999999
Random rnd = new Random();
int number = rnd.nextInt(999999);
// this will convert any number sequence into 6 character.
return String.format("%06d", number);
}

If you need a six digit number it has to start at 100000
int i = new Random().nextInt(900000) + 100000;
Leading zeros do not have effect, 000000 is the same as 0. You can further simplify it with ThreadLocalRandom if you are on Java 7+:
int i = ThreadLocalRandom.current().nextInt(100000, 1000000)

1 + nextInt(2) shall always give 1 or 2. You then multiply it by 10000 to satisfy your requirement and then add a number between [0..9999].
already solved here
public int gen()
{
Random r = new Random( System.currentTimeMillis() );
return ((1 + r.nextInt(2)) * 10000 + r.nextInt(10000));
}

i know it’s very difficult but you can do something like this:
create a class for BinaryNumber;
create a constructor that generate a char[] of 6 character where every single one is generated with a randomiser from 0 to 1
override the toStrig() method so that it will return the digits char[] as a string if you want to display it. then crate a method toInt() that esaminate the string char by char with a for and turn it in a decimal base number by multiplying current digit to 10 to the pow of i:
char[] digits = {‘1’ , ‘0’ , ‘1’ , ‘1’ , ‘0’ , ‘1’};
//random
int result = 0;
for( int i = 0; i < digits.length; i++) {
result += Integer.parseInt(digits[i]) * Math.pow(10, i);
}
return result;

This is the code in java which generate a 6 digit random code.
import java.util.*;
public class HelloWorld{
public static void main(String []args)
{
Random r=new Random();
HashSet<Integer> set= new HashSet<Integer>();
while(set.size()<1)
{
int ran=r.nextInt(99)+100000;
set.add(ran);
}
int len = 6;
String random=String.valueOf(len);
for(int random1:set)
{
System.out.println(random1);
random=Integer.toString(random1);
}
}
}

Related

How toMake Math.random generate number between 1 and 1000? [duplicate]

This question already has answers here:
How do I generate random integers within a specific range in Java?
(72 answers)
Closed 9 months ago.
So I'm trying to figure out how to print out a random number between 1 to 1000.
I tried:
double a = 1+ (Math.random()*1000);
System.out.println(a);
But when I try this i get numbers with a bunch of decimals. I do not want any decimals. Anyone can help? I want to get a value like 50 or 289 or 294. I do not want to get a number like 234.5670242
or 394.220345. Help if you can. will appreciate it. Thank you.
Try this:
public static void main(String args[])
{
// define the range
int max = 1000;
int min = 1;
int range = max - min + 1;
// generate random numbers within 1 to 1000
for (int i = 0; i < 1000; i++) {
int rand = (int)(Math.random() * range) + min;
// Output
System.out.println(rand);
}
}

Displaying 500 random integers [duplicate]

This question already has answers here:
How do I generate random integers within a specific range in Java?
(72 answers)
Closed 4 years ago.
I want to generate 500 random numbers and display them next to their indexes. I want the numbers to be 1 though 10. But when I run my code it only generates 13 random numbers and the numbers are greater than 10. Please help.
public class RandomStats {
public static void main(String[] args) {
int [] stats = new int [501];
int numRolls;
int outcome;
for (int i = 0; i <=500; i++ ){
outcome = (int) ( 10 * Math.random() + 1)
+ (int) ( 10 * Math.random () + 1);
stats[outcome] += 1;
}
for ( int i = 2; i <=500; i++) {
System.out.println(i + ": " + stats[i]);
}
}
}
While saving in the array, you are doing stats[outcome] += 1;, where your array is updated with same index again and again and thats the reason you only see ~13 values and rest as 0. I believe it should be stats[i] =outcome+ 1;

Using Random class to continue adding a random digit to a given number in Java

Given an integer, 234, how would I use a Random object to take this number and add only one random digit to it without making it a String. So the goal in this case would be to return a number that has 4 digits, with the last one being random. So for example the next number could be 2347. Then I want to take this number and do the same thing for 5 digits, for instance 23471. I know I can multiply by 10 to increase the digit count by 1, but this would not be random. The only methods I'm aware of for the Random class are nextInt(int n) and nextDouble().
Random generator = new Random();
int gameNum = 234;
public static int UpdateGameNum(int gameNum, Random)
{
gameNum = gameNum * 10 + generator.nextInt(10) would do it.
(The second argument to + is a random number in the inclusive range 0 to 9).
If you want to support negative gameNum, then use the more complex
gameNum = (gameNum >= 0 ? 1 : -1) * (Math.abs(gameNum) * 10 + generator.nextInt(10));
which effectively strips the sign, performs the concatenation of the random number, then reintroduces it.
You don't need to pass Random instance as an argument to updateGameNum()
Just multiply getNum with 10 and add a number from (0 - 9) by picking it randomly.
Random generator = new Random();
int gameNum = 234;
public static int UpdateGameNum(int gameNum)
{
return ( gameNum *10 ) + generator.nextInt(10);
}

generate a random number for a credit card

I am trying to use this method to generate a credit card number of 16 digits that starts with 4
if the issuerSymbol equals ISSUER AMER EXPRESS. the random number has to start with 3 if issuerSymbol equals ISSUER VISA and 5 it it ISSUER MASTER CARD.
public Integer getIssuerCode(String issuerSymbol){
int randomInteger = 0;
Random random = new Random();
for(int i = 0; i < 5; i++) {
randomInteger = random.nextInt();
if (issuerSymbol.equals(ISSUER_AMER_EXPRESS)) {
}
else {
System.out.println("error");
}
if(issuerSymbol.equals(ISSUER_VISA)){
}
else{
System.out.println("error");
}
if (issuerSymbol.equals(ISSUER_MASTER_CARD)){
}
else{
System.out.println("error");
}
}
return randomInteger;
}
I think you have a problem with you if and else. You need to understand that it will go in else if the if is not true the code should be changed to them to if else if and else ...
if (issuerSymbol.equals(ISSUER_AMER_EXPRESS)) {
} else if(issuerSymbol.equals(ISSUER_VISA)){
} else if (issuerSymbol.equals(ISSUER_MASTER_CARD)){
} else {
System.out.println("error");
}
Another suggestion the Random class includes nextInt(int) which (per the Javadoc) *Returns a pseudorandom, uniformly distributed int value between 0 (inclusive) and the specified value (exclusive), drawn from this random number generator's sequence.
randomInteger = 3 + random.nextInt() % 3;
or
randomInteger = 3 + random.nextInt(3);
this will ensure that you randomInteger is always in 3 or 4 or 5
With 16 digits, the biggest number for the credit card you can get is 5999999999999999, while the biggest number int can represent is 2^31-1 or 2,147,483,647, so I'd recommend using BigInteger instead. Depending on how you plan on using randomInteger, it can either be a BigInteger or a String.
Since you're trying to get a 16 digit number but the first is determined to be either 3, 4, or 5, that means you need 15 random integers. You can set randomInteger based on the issuer symbol using your if-else if statements, then you can use a for loop that picks 15 random integers and appends them to randomInteger.
//assuming randomInteger is already equal to 3, 4, or 5
//and randomInteger is of type BigInteger
for(int i = 0; i < 15; i++)
{
randomInteger = randomInteger.multiply(BigInteger.valueOf(10);
randomInteger = randomInteger.add(BigInteger.valueOf(random.nextInt(10));
}
If you wanted randomInteger to be a string, just concatenate the first digit to an empty string ("") and keep concatenating a random digit.

making a 13 digit random number generator in Java

a friend of mine at Uni, was wanting to generate a bunch of 13 digit numbers so he can test his sorting algorithms on, but was doing it a very long way around, so i've tried to use the following code to generate a settable number of 13 digit numbers.
public class random {
public static void main(String[] args) {
long intArray[] = new long[20]; // to generate more than 20 random numbers increase this and the 'i < 20' to the same number ie. 75
for(int i = 0; i < 20; i++) { // here
intArray[i] = numbGen();
}
for(int j = 0; j < intArray.length; j++) {
System.out.println(intArray[j]);
}
}
public static long numbGen() {
long numb = (long)(Math.random() * 10000000 * 1000000); // had to use this as int's are to small for a 13 digit number.
return numb;
}
}
my issue is now sometimes it will generate a couple of 12 digit numbers in the group of 20 and i want to find a way not to add the number to the array if it is not 13 digits. I've tried if statement but getting stuck on not being able to determine the length (individual characters) of the Long.
Thanks in Advance.
A simple solution:
while(test < 10000) {
long num = (long) (Math.random() * 100000000 * 1000000);
if(Long.toString(num).length() == 13) {
return num;
}
test++;
}
However, a better solution is this:
long number = (long) Math.floor(Math.random() * 9000000000000L) + 1000000000000L;
This will only generate random 13 digit numbers, and you don't need to check if there are more or less digits.
Note that this solution may not scale to a higher number of digits and may not return a perfect distribution of random numbers.
long min = 1000000000000L; //13 digits inclusive
long max = 10000000000000L; //14 digits exclusive
Random random = new Random()
long number = min+((long)(random.nextDouble()*(max-min)));
A generic integer based implementation would be:
public static long randomDigits(int digits) {
if (digits <= 0 || digits > 18) {
throw new IllegalArgumentException("A long can store the random of 18 full digits, you required: " + digits);
}
// use SecureRandom instead for truly random values
final Random r = new Random();
long randomNumber = r.nextInt(9) + 1;
for (int i = 1; i < digits; i++) {
randomNumber = randomNumber * 10L + (long) r.nextInt(10);
}
return randomNumber;
}
or use a shorter version for 13 digits that does not tax the RNG as much:
public static long thirteenRandomDigits() {
final Random r = new Random();
return 1_000_000_000L * (r.nextInt(9_000) + 1_000)
+ r.nextInt(1_000_000_000);
}
These solutions are better to using Math.random() because they don't rely on multiplication with a large number to generate the random values. A double only has 15-17 digits precision, which is very close to the 13 digits number it is multiplied with. This leads to unequal distributions of random numbers. Solutions based on Math.random() won't scale past 13 digits either.
The simple solution for the problem that you described:
public static long numbGen() {
while (true) {
long numb = (long)(Math.random() * 100000000 * 1000000); // had to use this as int's are to small for a 13 digit number.
if (String.valueOf(numb).length() == 13)
return numb;
}
}
This is not the most efficient or most random implementation of generating a 13-digit number but it answers your specific question.
ThreadLocalRandom is a good thing, introduced in Java 1.7
java.util.concurrent.ThreadLocalRandom
.current()
.nextLong(1000000000000L, 10000000000000L);
long randomNumber = 0;
long power = 1;
for(int i = 0; i < 12; i++) { // up to 12 not 13
Random r = new Random();
int randomInt = r.nextInt(10);
randomNumber += (power * randomInt);
power *= 10;
}
// here, the most stupid way to provide last digit to be not zero
Random r = new Random();
int randomInt = r.nextInt(9);
randomInt++;
randomNumber += (power * randomInt);
power *= 10;
First off, a Long doesn't have characters.
If you want to see if it has 13 digits, compare it to 999999999999L.
If you want to insure you have a value w/ 13 digits, get a random number between 0 and 8999999999999L (inclusive) (using the technique you already have to generate a random number in a range) and add it to 1000000000000L.
Why not we try with Unix timestamp in milliseconds.Because that will work for next 200 years and after that we need to only eliminate the trailing digit from the number.
Calendar.getInstance().get(Calendar.MILLISECOND);
and by using this method we don't need any loop or any condition and it will give me a unique number every time.

Categories

Resources