Generate random integer between 100 and 2000 in steps of 100 Java - java

Im currently trying to get a random integer between 100 and 2000 in steps of 100 like 300, 800, 1400 etc.
Thats what I found to get a random number between a range, but how do I manage to get a random number in steps of 100?
Random random = new Random();
int start = 100;
int end = 2000;
int result = random.nextInt(start - end) + start;

The problem is whether you want 2000 included or not. And whether the step size reaches 2000 exactly. The calculation just needs to include the step size:
Random random = new Random();
final int start = 100;
final int end = 2000;
final int step = 100;
int result = start + step * random.nextInt((end - start)/step); // end excl.
int result = start + step * random.nextInt((end - start)/step + 1); // end incl.
As already commented, it is probably more clear to base all on a random number between 1 and 20, and scale that up.
int result = (1 + random.nextInt(20)) * 100; // 100 upto 2000 by 100.

Related

value zero generated numerously using random function() [duplicate]

This question already has answers here:
How do I generate random integers within a specific range in Java?
(72 answers)
Closed 7 years ago.
/*This is my function code*/
Random random = new Random();
int randomInt = random.nextInt()%200;
String imgName = "img" + randomInt;
int ImageId = getResources().getIndentifier(imgName,"drawabale",getPackageName());
myImage.setImageResourse(ImageId);
Previously in my drawable folder there are
200 images already inserted using img1,img2.....img199
like nomenclature...
every time I call random function mention below to generated one
random number and form a string name starting from
"img" and some number. But most of time only 0 is generated by random function and id set to
image is display 0th image constantly..at some point it successfully display other images but most of time it generated zero value continuosly.
Thanks in Advance !
You can generate Random number with specific Range
Random r = new Random();
int randomInt = r.nextInt(maxVal - minVal) + minVal
For your example
int randomInt = r.nextInt(200 - 1) + 1
Will generate number between 1 to 199.
A random number generated by nextInt should be a multiple of 200 at random, i.e. one every 200 or so. This test suggests this is happening correctly:
public void test() {
Random random = new Random();
final int tests = 200000;
int twoHunderdIsAFactor = 0;
for (int i = 0; i < tests; i++) {
if (random.nextInt() % 200 == 0) {
twoHunderdIsAFactor += 1;
}
}
System.out.println("Tests = " + tests + " Hits = " + twoHunderdIsAFactor + " Proportion = " + (tests / twoHunderdIsAFactor));
}
prints Tests = 200000 Hits = 1012 Proportion = 197 - i.e. about 200 times for 200000 randoms.
Generating randoms in a specific range is dealt with in other answers.

random number with range and multiplier in java

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;

Getting a range off user input for random generation

So I am trying to get my code to get a random number generation based off what the user inputs. and my current statement doesnt generate the proper range.
secretNum = low + (int)(Math.random()* max);
Where low is the lowest part of the range, and high is the highest. For example. if low was 5 and high was 10, would this generate a range from 1-50? (5*10).
I'd use a Random object for this.
You create it like this:
Random r = new Random();
And then from there, it is very easy to use. For a random int from 0 (inclusive) to 50 (exclusive), just do:
int randomNumber = r.nextInt(50);
I think it makes all of this much easier for you. If the user inputs 10 and 140, then you do something like this:
int lowest = 10;
int highest = 140;
int randomMax = 140-10;
int randomNumber = r.nextInt(randomMax) + 10;
It's probably the easiest way to do this.
You save your user input in the variable in:
String in = sc.nextLine();
Then you create a instance of java.util.Random with the seed being a hash of the input:
Random r = new Random(in.hashCode());
int randomNumber = r.nextInt();
If you want to generate a random number between with a maximum and a minimum see this Question
Or this one but then you need to convert c++ into java:
C++:
output = min + (rand() % (int)(max - min + 1))
Java:
output = min + (r.nextInt() % (max - min + 1))
You can also use r.nextInt(max) if you only need a maximum.
Note:
For cryptographically secure random numbers use an instance of SecureRandom

Re-Generate Random Number. Android?

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

Array index out of bounds: 30 (Java)

I am writing a program to print out a user inputed integer into binary form.
When I run it and input, say the number 5, it crashes and gives me the error:
java.lang.ArrayIndexOutOfBoundsException: 30
at PrintBinaryDigitsFixed.main(PrintBinaryDigitsFixed.java:27)
i.e the line "digits[counter] = number % 2;"
Why am I getting an out of bounds exception? It should assign the remainder to the first element then move on to the second shouldn't it?
I feel like I'm making a glaringly obvious mistake but I can't tell what it is
final int MIN = 0;
final int MAX = (int) (Math.pow(2, 30) - 1);
int[] digits = new int[30]; //array to hold the digits
int number = readInput
("Enter an integer from " + MIN + " to " + MAX, MIN, MAX);
int counter = 0;
int modNumber = 2;
while(modNumber / 2 != 0)
{
digits[counter] = number % 2;
modNumber = number / 2;
counter++;
}
System.out.print(number + " in binary form is ");
listBackwardsFrom(digits, counter);
Thanks
You never change number in your loop, and you assign modNumber = number / 2 in the loop, so from the second iteration onward modNumber is a constant (for most of the first iteration it's 2, but then you assign number / 2 to it); if you reach that point at all, you'll stay there. So the loop continues until counter reaches 30, at which point digits[counter] throws the exception.

Categories

Resources