I am trying to re-generate random numbers in android. I want to generate two numbers which are divisible by each other. If the generated numbers are not divisible, I want the system to try again until it generates numbers which are divisible by each other.
Here is my code:
Random random = new Random();
arrone = random.nextInt(100 - 20) + 20;
Random randm = new Random();
arrtwo = randm.nextInt(11 - 2) + 2;
if (arrone % arrtwo ==0){
// if they are divisible do this.
} else {
// if they are not divisible, I want it to try again and find two divisble numbers
}
To rephrase the problem, you want two numbers where one is a multiple of the other. The significant difference is you don't need to use a loop to find such a pair of values.
int min = 20;
int max = 100;
int second = rand.nextInt(11 - 2) + 2;
int multiplier = Math.max((min + second-1)/second,
rand.nextInt(max / second) + 1);
int first = multiplier * second;
In this case, you know the first must be divisible by the second.
boolean divisible = false;
while (!divisible ) {
Random random = new Random();
arrone = random.nextInt(100 - 20) + 20;
Random randm = new Random();
arrtwo = randm.nextInt(11 - 2) + 2;
if (arrone % arrtwo == 0){
// if they are divisible do this.
divisible = true;
}
}
}
Related
The assignment is to flip a coin until four heads in a row are seen and display all the results leading up to that. I keep getting the last error message I put in just in case it fell through. I have no idea what I messed up and was wondering if someone was able to help.
class Main {
public static void main(String[] args) {
int h = 2;
int t = 1;
int count = 0;
int result;
while (count<=4)
{
result = (int)Math.random()*2;
if (result == 2)
{
count++;
System.out.print("H ");
}
else if (result == 1)
{
count=0;
System.out.print("T ");
}
else
System.out.println("error");
}
}
}
(int)Math.random() * 2
is the same as
((int)Math.random()) * 2
Given that Math.random() returns a number at least zero but less than one, your expression is always going to be zero.
Put in parentheses:
(int) (Math.random() * 2)
But then, also look at the values of result in your conditionals: you will never generate 2.
You need to add 1 to have possible values of one or two:
result = (int) (Math.random() * 2 + 1);
You can use the Randomclass and boolean
Random random = new Random();
int count = 0;
while (count < 4) {
if (random.nextBoolean()) {
System.out.print("H");
count++;
} else {
count = 0;
System.out.print("T");
}
}
As the result of Math.random() is between 0 and 1 type casting it to int will remove the digits after decimal point and you'll always have zero as answer.
Below code will help you to generate a random number between min and max.
// define the range
int max = 2;
int min = 1;
int range = max - min + 1;
int rand = (int)(Math.random() * range) + min;
For an explanation of how this works you can put the min possible value of 0 and max possible of 0.99 and multiply both by any range, let's say 20 the answer will still be in between 1 to 20.8 which gets turned to 20 as it's not rounding off but directly type casting. Hence, this can give you a random number for any range.
I'm trying to make a program that generates random two-digit integers until I get a 10 or a 20. To then find the mount of numbers, the sum of the numbers less than 10, the sum of the numbers equal to 15, the sum of the numbers greater than 70. Can someone help me, please?
This is my code:
// Variables
int numRandom = 0, less10, equal15, more70;
// Process
txtS.setText("Random numbers: " + "\n");
for (int mountNum = 0; numRandom == 40 || numRandom == 20; mountNum++) {
numRandom = (int) (99 * Math.random());
txtS.append(numRandom + "\n");
}
You could just store the values directly and create variables for each case.
This is an example for you less than 10 case. (The 'if statement' would be contained inside your for loop).
int sumLessThanTen = 0;
int countLessThanTen = 0;
...
if(numRandom < 10){
sumLessThanTen += numRandom;
countLessThanTen++
}
I'm trying to generate a random number within a range, and of a specific multiple. My example would be within the range of 60 - 500, and only multiples of 5, e.g. 60, 65, 70 -> 500
I'm trying to use random.nextInt(), but I can either get the range to work, or the multiplier, but not both.
Any assistance would be greatly appreciated!
I'd work my way backwards - generate a random number and then multiply it by the multiple you want:
int multiple = 5;
int rangeStart = 60;
int rangeEnd = 500;
int calcRangeStart = rangeStart / multiple;
int calcRangeEnd = rangeEnd / multiple;
int random = new Random().nextInt(calcRangeStart, calcRangeEnd) * multiple;
First work out the number of possible values for your random number, which is
((500-60)/5 + 1) or
((505-60)/5)
using integer division. Using this value as an argument to Random.nextInt will give you values starting from 0. So you just need to multiply by 5 and add 60 to get values in your desired range
Random random = new Random();
(random.nextInt((505-60)/5) * 5 + 60)
You can define your from-to and multiply numbers as ints and then generate them like this:
int from = 60, to = 500, multi = 5;
Random rand = new Random();
int n = multi*(Math.round(rand.nextInt((to+multi-from))+from)/multi);
This code will generate numbers from 60 to 500 in multiplies of 5 only.
int seed = 5;
Random random = new Random();
int inf = 12;
int sup = 100;
int number = random.nextInt((sup-inf)+1) + inf;
number *= seed;
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.
I am trying with below code to generate 10 digits unique random number. As per my req i have to create around 5000 unique numbers(ids). This is not working as expected. It also generates -ve numbers. Also sometimes one or two digits are missing in generated number resulting in 8 or 9 numbers not 10.
public static synchronized List generateRandomPin(){
int START =1000000000;
//int END = Integer.parseInt("9999999999");
//long END = Integer.parseInt("9999999999");
long END = 9999999999L;
Random random = new Random();
for (int idx = 1; idx <= 3000; ++idx){
createRandomInteger(START, END, random);
}
return null;
}
private static void createRandomInteger(int aStart, long aEnd, Random aRandom){
if ( aStart > aEnd ) {
throw new IllegalArgumentException("Start cannot exceed End.");
}
//get the range, casting to long to avoid overflow problems
long range = (long)aEnd - (long)aStart + 1;
logger.info("range>>>>>>>>>>>"+range);
// compute a fraction of the range, 0 <= frac < range
long fraction = (long)(range * aRandom.nextDouble());
logger.info("fraction>>>>>>>>>>>>>>>>>>>>"+fraction);
int randomNumber = (int)(fraction + aStart);
logger.info("Generated : " + randomNumber);
}
So you want a fixed length random number of 10 digits? This can be done easier:
long number = (long) Math.floor(Math.random() * 9_000_000_000L) + 1_000_000_000L;
Note that 10-digit numbers over Integer.MAX_VALUE doesn't fit in an int, hence the long.
I think the reason you're getting 8/9 digit values and negative numbers is that you're adding fraction, a long (signed 64-bit value) which may be larger than the positive int range (32-bit value) to aStart.
The value is overflowing such that randomNumber is in the negative 32-bit range or has almost wrapped around to aStart (since int is a signed 32-bit value, fraction would only need to be slightly less than (2^32 - aStart) for you to see 8 or 9 digit values).
You need to use long for all the values.
private static void createRandomInteger(int aStart, long aEnd, Random aRandom){
if ( aStart > aEnd ) {
throw new IllegalArgumentException("Start cannot exceed End.");
}
//get the range, casting to long to avoid overflow problems
long range = aEnd - (long)aStart + 1;
logger.info("range>>>>>>>>>>>"+range);
// compute a fraction of the range, 0 <= frac < range
long fraction = (long)(range * aRandom.nextDouble());
logger.info("fraction>>>>>>>>>>>>>>>>>>>>"+fraction);
long randomNumber = fraction + (long)aStart;
logger.info("Generated : " + randomNumber);
}
I don't know why noone realized that but I think the point is to generate "unique" random number which I am also trying to do that. I managed to generate 11 digits random number but I am not sure how to generate unique numbers. Also my approach is a little different. In this method I am appending number chars next to each other with for loop. Then returning long number.
public long generateID() {
Random rnd = new Random();
char [] digits = new char[11];
digits[0] = (char) (rnd.nextInt(9) + '1');
for(int i=1; i<digits.length; i++) {
digits[i] = (char) (rnd.nextInt(10) + '0');
}
return Long.parseLong(new String(digits));
}
I would use
long theRandomNum = (long) (Math.random()*Math.pow(10,10));
A general solution to return a 'n' digit number is
Math.floor(Math.random() * (9*Math.pow(10,n-1))) + Math.pow(10,(n-1))
For n=3, This would return numbers from 100 to 999 and so on.
You can even control the end range, i.e from 100 to 5xx but setting the "9" in the above equation "5" or any other number from 1-9
This is a utility method for generating a fixed length random number.
public final static String createRandomNumber(long len) {
if (len > 18)
throw new IllegalStateException("To many digits");
long tLen = (long) Math.pow(10, len - 1) * 9;
long number = (long) (Math.random() * tLen) + (long) Math.pow(10, len - 1) * 1;
String tVal = number + "";
if (tVal.length() != len) {
throw new IllegalStateException("The random number '" + tVal + "' is not '" + len + "' digits");
}
return tVal;
}
Maybe you are looking for this one:
Random rand = new Random();
long drand = (long)(rand.nextDouble()*10000000000L);
You can simply put this inside a loop.
this is for random number starting from 1 and 2 (10 digits).
public int gen() {
Random r = new Random(System.currentTimeMillis());
return 1000000000 + r.nextInt(2000000000);
}
hopefully it works.
Hi you can use the following method to generate 10 digit random number
private static int getRndNumber() {
Random random=new Random();
int randomNumber=0;
boolean loop=true;
while(loop) {
randomNumber=random.nextInt();
if(Integer.toString(randomNumber).length()==10 && !Integer.toString(randomNumber).startsWith("-")) {
loop=false;
}
}
return randomNumber;
}