generate a random number for a credit card - java

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.

Related

How many bases b are there such that the base b representation of number starts with a 1?

The problem statement is :
Problem Statement-: Altaf has recently learned about number bases and is becoming fascinated.
Altaf learned that for bases greater than ten, new digit symbols need to be introduced, and that the convention is to use the first few letters of the English alphabet. For example, in base 16, the digits are 0123456789ABCDEF. Altaf thought that this is unsustainable; the English alphabet only has 26 letters, so this scheme can only work up to base 36. But this is no problem for Altaf, because Altaf is very creative and can just invent new digit symbols when she needs them. (Altaf is very creative.)
Altaf also noticed that in base two, all positive integers start with the digit 1! However, this is the only base where this is true. So naturally, Altaf wonders: Given some integer N, how many bases b are there such that the base-b representation of N starts with a 1?
Input Format :
The first line of the input contains an integer T denoting the number of test cases. The description of T test cases follows.
Each test case consists of one line containing a single integer N (in base ten).
Output Format :
For each test case, output a single line containing the number of bases b, or INFINITY if there are an infinite number of them.
Constraints:
1 <= T <= 10^5
0 <= N < 10^12
Sample Input
4
6
9
11
24
Sample Output:
4
7
8
14
Explanation:
In the first test case, 6 has a leading digit 1 in bases 2, 4, 5 and 6: 610 = 1102 = 124 = 115 = 106.
I trying this in java , But at some point my loop is not working it only takes the first value and after that it will come out of the loop!! Thank you
My code :
import java.util.*;
public class MyClass {
public static void main(String args[]) {
Scanner sc = new Scanner(System.in);
long n,i,j,k,m;
long count=0,rem1,index;
long rem[];
rem = new long[(int)100];
int t = sc.nextInt();
for(i=1;i<=t;i++)
{
n = sc.nextInt();
j=2;
while(j<=n)
{
// for(j=2;j<=n;j++)
// {
index=0;
m = j;
while(n>0)
{
rem1 = n%m;
rem[(int)index++] = rem1;
n = (long) (n / m);
}
// for(k=index-1;k>=0;k--)
// {
if(rem[1]==1)
{
count++;
}
// }
j++;
}
System.out.println(count);
// }
}
}
}
I'm not sure I follow the logic in the loop (and, by your own admission, there's a problem there).
The logic of the loop (i.e., "how many bases represent the number N with a representation starting by 1"), can be greatly simplified.
The first step is finding the highest power of the base B required to represent the number N. This is given by logb(n), truncated to the nearest integer. Java doesn't have a built-in log function with a variable base, but you can get this result by calculating log(n)/log(b).
Then, you need to find the digit in this position. This can be calculated by dividing N by Bpower using integer division.
From there on, you just need to check if the result is 1, and if so, record it.
Put it all together and you'll end up with something like this:
private static int howManyBasesStartWithOne(int num) {
int count = 0;
for (int i = 2; i <= num; ++i) {
int highestBase = (int) (Math.log(num) / Math.log(i));
int leadingDigit = num / (int) Math.pow(i, highestBase);
if (leadingDigit == 1) {
++count;
}
}
return count;
}

Generate 6 digit random number [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 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);
}
}
}

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);
}

Bad Operand types - First type - java.util.Random, Second type - int

I am trying to create a program where a slot machine takes a random int, process it with some if statements for a range of numbers, and returning an amount of cash based on what range of numbers the random integer fits into.
The problem derives from the if statement, if(s >= 0 && s < 6 ), where I am comparing a random object with an int.
/* This method determines the amount of pay off when there is a winner
* # return the amount of payoff
*/
private int getPayOff()
{
Random s = new Random();
s.nextInt(11);
Random rr = new Random();
rr.nextInt(10 + 1);
Random rrr = new Random();
rrr.nextInt(90 + 11);
if(s >= 0 && s < 6 )
return rr;
else if(s >= 6 && s < 9)
return rrr;
return 10000;
}
If I understand your question, you want to generate two values in the range1 1 to 10 and one in the range 11 to 100. You only need one Random (a generator for random values), and then you can use it to generate three random values (actually, two random values depending on the code path). Also, you can simplify your if chain to remove impossible conditions. Something like,
private final Random rand = new Random(); // <-- one.
private int getPayOff() {
int s = 1 + rand.nextInt(10); // <-- [1,10]
if (s < 6) {
return 1 + rand.nextInt(10); // <-- [1,10]
} else if (s < 9) {
return 11 + rand.nextInt(90); // <-- [11,100]
}
return 10000;
}
1We add one because Random.nextInt(int) returns a pseudorandom, uniformly distributed int value between 0 (inclusive) and the specified value (exclusive).

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