Generate random numbers increasing by multiples of N in Java - java

I need to write a short randomizer which generates a random number between 1 to N where the random number is increasing by multiples of M.
For example: generate numbers between 1 and (N=30) increasing by multiples of (M=5). The only possible generated numbers can be then: 1,5,10,15,20,25 and 30. Hope you get what I mean :)
Normally if you use new Random().nextInt(30)+1, you get numbers increasing by multiples of 1 (1,2,3,4,5,6,7,etc.). That is not what I want.
Any help, links, or directions are very appreciated?
EDIT:
That the sequence of generated random numbers could include 1 not zero is one of the requirements of the method. Precisely, the sequence always starts with the lower bound (min). In the example the lower bound is 1 and therefore there can't be zero in the sequence. It's odd I know, but those are the requirements I have to follow ;)

You could multiply the random value by 5. Since you want to have 1 instead of 0 just look for that value and alter it specifically:
static final Random random = new Random(System.currentTimeMillis());
public int random(int range, int multiple) {
int value = random.nextInt(range / multiple) * multiple;
return value == 0 ? 1 : value;
}

I think that your example is a little bit flawed: the sequence should be (0, 5, 10, 15, 20, 25, 30)
If I'm correct, you can then use:
new Random().nextInt(7) * 5; // will generate a number between 0 and 7 not included then multiply by 5 which should give what you want
If you want to start by 1, then just add it to the previous statement

Try this..
public static void main(String[] args){
int N = 50;
int M = 5;
System.out.println(getRandomNumber(N, M));
}
static int getRandomNumber(int n, int m){
Random r = new Random();
int rnd = r.nextInt(n);
return rnd%m == 0?rnd:getRandomNumber(n, m);
}

int n=Random.range(1,10);
n=n*100;

Related

Why is the result of my int multiplication wrong?

I have the the following code where the results exceeds the limit an integer type variable can store and need to understand why I am getting this result (268,435,456=2^28)
public static void main(String[] args) {
int x = 16+256;
for( int i =0; i<6; i++) {
x*=16;
}
System.out.println(x);
}
}
Consider how this looks with all the values expressed in binary.
Initially, x = 00000000000000000000000100010000. Then every time you multiply by 16, you add 4 zeroes to the right, and remove 4 digits from the left.
So you get results like
00000000000000000001000100000000
00000000000000010001000000000000
and so on. But once you've done this 6 times, the first 1 disappears off the left end of the number - this is the integer overflow. So you're left with
00010000000000000000000000000000
which is 2 to the 28.

Java Random number but not zero

int num = 10;
Random rand = new Random();
int ran = rand.nextInt(num);
if (ran==0){
ran= ran+1;
}
System.out.println("random : "+ran);
This is what i have coded so far, is there a better way to do this? I feel that this is hard coding when random is 0, I added 1.
The problem with that code is that 1 is twice as likely as other numbers (as your effective result is 1 when nextInt() returns 0 or 1).
The best solution is to just always add 1 and request random numbers from a smaller range:
int rnd = rand.nextInt(num - 1) + 1;
I guess you are trying to get a random number between 1 and 'num'.
a more generic way can be :
int Low = 1;
int High = 10;
int R = r.nextInt(High-Low) + Low;
This gives you a random number in between 1 (inclusive) and 10 (exclusive). ( or use High=11 for 10 inclusive)
Random random = new Random();
int ran = random.nextInt(9) + 1; //10 is maxRandom value for this code. 1-10
you also could do the following:
int randomNumber = 0;
do {
randomNumber = rand.nextInt(maxValue);
} while(randomNumber == 0);
Try this:
int num,max=10,min=1;
Random r=new Random();
num=r.nextInt(max-min)+1;
You'll need this import at the beginning of your file:
import java.util.Random;
Just lower the bound (num variable) by 1 and add 1 to the ran variable
int num = 10;
Random rand = new Random();
int ran = rand.nextInt(num - 1) + 1;
// or decrease num first n-- and then int ran = rand.nextInt(num) + 1
now the bound(limit) is 8 (inclusive for example, the final number is always exclusive) and if it comes 0, it will increase to 1 and if it comes 8, it will increase to 9, which was originally supposed to be the bound.
Don't expect this functionality from Random and do it yourself as you should. One can do pretty much anything with the result - multiply, add (e.g. 2*nextInt(n)+1 for random odd number), use logarithmic scale for musical note frequencies, use a map or enum to obtain random objects ...
Method nextInt(n) is here only to give you n different values (from 0 to n-1). Don't ask more of it, implement the rest by yourself. If I understand your question well, you require numbers 1..9, so you should ask for nextInt(9)+1 to get 0..8 and then add 1.
I hope this explanation helps, I saw many answers, but I didn't like the explanation in any of them.
Try:
int num = 10;
Random rand = new Random();
int ran = rand.nextInt(num) + 1;

How to create unique random numbers from a given Random generator

Write an efficient algorithm to print the following two outputs
You are given a pre-defined function named getrand100() 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().
int getrand100(){
Random rand = new Random();
return (1+rand.nextInt(100));
}
Output1: Print numbers 1-20 in random order. (Not 20 random numbers)
Output2: Print numbers 1-200 in random order. (Not 200 random numbers)
Note:
i. Every number should be printed exactly once.
ii. There should be no pattern in the numbers listing. List should be completely random
i.e., all numbers have equal probability appearing at any place.
iii. You may call getrand100() any number of time to get randomnumber
from 1 to 100.
iv. You cannot use any other random generator
function except getrand100().
The idea is to use the Random generator given to compute the required random numbers.
1) For random numbers 1-20, just divide the 100 numbers equally to represent 1 to 20.
2) To generate 1-200, find the even numbers from 1 to 200 and then add (-1 or 0) to it to get all the numbers from 1 to 200.
import java.util.*;
public class Rand20_200{
int number20[]=new int[20]; //numbers in random order
int number200[]=new int[200];
public Rand20_200(){
int n=0;
int ngen[]=new int[20]; //to store which random numbers are generated
while(n<20){
int rnd=1 + (getrand100()-1) / 5;
if (ngen[rnd-1]==0){
ngen[rnd-1]=1;
number20[n++]=rnd;
}
}
System.out.println("Random 20 numbers");
print(number20);
ngen=new int[200]; //to store which random numbers are generated
int numoff[]={-1,0}; //offset to add
n=0;
while(n<200){
int rnd=numoff[(getrand100()-1)/50]+ (getrand100()*2);
if (ngen[rnd-1]==0){
ngen[rnd-1]=1;
number200[n++]=rnd;
}
}
System.out.println("\nRandom 200 numbers");
print(number200);
}
int getrand100(){
Random rand = new Random();
return (1+rand.nextInt(100));
}
void print(int arr[]){
for(int i=0;i<arr.length;i++){
System.out.print(arr[i]+" ");
}
}
public static void main(String args[]){
new Rand20_200();
}
}
Assuming this is homework, I'll keep the answer terse. :)
Look into the modulus operator %
You could create a list with your value (1 - 20, 1 - 200) and a random number, then sort the list on the random number.
public class RandomListItem
{
int value;
int sortindex;
public RandomListItem(x,y)
{
value = x;
sortindex = y;
}
}
for(int i = 1; i <= maxvalue; i++)
{
list.add(new RandomListItem(i, getrand100());
}
This might not be so good for the 200 list, since you can only generate random numbers up to 100. Might want to use getrand100() * getrand100() or something to generate a wider range of random numbers.

a random number from an array

I have an array
(1,2,2,2,3,3,4,5,5,5,5,5,5)
I must find randomly one position taking into account the sum of elements. for example if the 5 - is six times and the 1 - is only one, so the 5 must six times be often in random
Something like this?
int array[] = {1,2,2,2,3,3,4,5,5,5,5,5,5};
int randomIndex = Random.nextInt(array.length);
int randomNumber = array[randomIndex];
You need to get a random index of the array:
int randomIndex = Random.nextInt(array.length);
int randomValue = array[randomIndex]
Like another answer said, you need an int in the range 0 : length-1.
I would advise using:
Random r = new Random();
int index = r.nextInt(array.length);
int randomValue = array[index];
Here you can see the differences between Math.random() and the nextInt() method of a Random Object:
Math.random() versus Random.nextInt(int)
try this:
1 import java.util.Random;
2
3 class Rnd {public static void main(String... args) {
4 int[] data = new int[]{1,2,2,2,3,3,4,5,5,5,5,5,5};
5 System.out.print(data[new Random().nextInt(data.length)]);
6 }
7 }
nextInt() method "Returns a pseudorandom, uniformly distributed int value between 0 (inclusive) and the specified value (exclusive), drawn from this random number generator's sequence.". Because random is uniformly distributed, you'll get your number as more often, as more often it includes in an array.

What is the best way to create a random value?

I am triying to create random value for my game to show enemies on screen. BUt it some times shows 2 together some times 3 ...I want to ask that which is the best formul for creating random value.. This is my so far random value
random = 1 * (int) (Math.random() * 100);
"BUt it some times shows 2 together some times 3"
Given perfectly random numbers... In every 100 random values from 0 to 99, you'll find an average of 1.0 doubles. A triple will occur on average once for every 10,000 values. Given 10 million random numbers, java.util.Random yeilds the following results on my machine:
Doubles: 99873
Triples: 985
Double Rate: 1 in 100
Triple Rate: 1 in 10152
Source code:
import static java.lang.System.*;
import java.util.Random;
public class Sandbox {
public static final int NUM_ITERATIONS = 10000000;
public static void main(String[] args) {
Random rand = new Random();
int cur;
int last = -1;
int secondLast = -2;
int nDoubles = 0;
int nTriples = 0;
for (int i = 0; i < NUM_ITERATIONS; i++) {
cur = rand.nextInt(100);
if (cur == last) {
nDoubles++;
if (cur == secondLast) nTriples++;
}
secondLast = last;
last = cur;
}
out.println("Doubles: " + nDoubles);
out.println("Triples: " + nTriples);
out.println();
out.println("Double Rate: 1 in " + Math.round(1.0 * NUM_ITERATIONS / nDoubles));
out.println("Triple Rate: 1 in " + Math.round(1.0 * NUM_ITERATIONS / nTriples));
exit(0);
}
}
Actually the creation of genuinely random random numbers is a complex game in its own right. The Wikipedia article on this subject will give you an insight into the complexity that lies therein. Simple approximations such as those outlined above are probably sufficient for game purposes but will, it should be noted, be inclined to be 'streaky' from time to time.
You can use java.util.Random:
Random random = new Random(); // uses System.nanoTime() as seed
int enemies = random.nextInt(100);
Anyway, your approach is also fine, as it is in fact equivalent (behind the scene) with the above.
You can print a sequence of 100 random numbers generated your way and see for yourself that there isn't a problem.
What you use if perfectly fine.
In case you want something simplier you might like to use Random class like this:
Random generator = new Random(seed);
int number = generator.nextInt(100);
...and sometimes 77, sometimes 23, etc, as expected in a uniform distribution?
If you would like a normal distribution instead for your "enemies", so that extremes are less likely, it seems to be there in Java.

Categories

Resources