How do I generate random numbers within a range - java

computerTotal = (int) Math.ceil(Math.random() * 21);
Can someone show me how to get 16 - 21 random number I keep getting errors when i try to implement the Math.floor function... As you can see i'm not very good at putting functions within functions.
Many Thanks!

If Java, use the Random Class.
Random r = new Random();
int myRand = 16+ r.nextInt(6); //16+[0-6) = 16-21

For creating random numbers between (including) min and max, you can do this:
Math.floor(Math.random() * (max - min + 1)) + min
Edit: The JAVA tag was added only after I suggested this; before it had no tags hinting at a specific language at all – so that there might be better/already implemented methods for this in language X is well possible. This is a very generic approach.

Related

Random numbers and while loop issues

I have to generate two random numbers for 52000 instances in an ArrayList, attack 1 and attack 2, where attack 1 must be greater than attack 2, so i have to put them in the list. This is my sample code:
do {
atk_p1 = (int) (Math.random() * (5000-500+1)+500);
atk_p2 = (int) (Math.random() * (5000-500+1)+500);
} while(atk_p1 <= atk_p2);
data.add(String.valueOf(atk_p1));
data.add(String.valueOf(atk_p2));
My problem is that the above code sometimes works (thus atk_p1 is greater than atk_p2) but other times not (thus atk_p2 is greater than atk_p1). I'm trying to solve the issue. Thank you for your help.
The above code is Java.
Another approach would be to generate a and b and then do simple comparison check to see if b is smaller than a.
If it is not you simply swap a and b.
I would just generate the second random number with the first one as it's upper limit:
atk_p1 = (int) (Math.random() * (5000-500+1)+501);
atk_p2 = (int) (Math.random() * (atk_p1)+500);
data.add(String.valueOf(atk_p1));
data.add(String.valueOf(atk_p2));
I solved in this way:
int atk_p1 = 0;
int atk_p2 = 0;
data.add(String.valueOf(atk_p1));
data.add(String.valueOf(atk_p2));
do{
atk_p1 = (int) (Math.random() * (5000-500+1)+500);
atk_p2 = (int) (Math.random() * (5000-500+1)+500);
}while(atk_p1 == atk_p2);
if(atk_p1 > atk_p2){
data.set(34, String.valueOf(atk_p1));
data.set(36, String.valueOf(atk_p2));
}else{
data.set(34, String.valueOf(atk_p2));
data.set(36, String.valueOf(atk_p1));
}
The problem was the arraylist.add() operation, it is not strict to the sequential order of the instructions. Using indexes to specify where to put the information worked great.
If you want to generate two random numbers, a and b, such that a < b, then
Generate a.
Generate b as a plus a random number greater than zero.
EDIT: This is wrong, and I admit it. See comments below. Mea culpa.

Guava - how can I generate a random number using Range?

Google's Guava library provides a great class called Range, it has many useful methods like greaterThan(x), open(x,y), etc. I am wondering if there is any way of applying such method to generate a random number within a Range?
I would not suggest using a range for this basic application.
The easiest method to use is the already implemented Random class.
Here is how to use the class:
For getting a random integer of any value:
Random r = new Random();
r.nextInt();
For getting a random integer in a range of min x, max y:
Random r = new Random();
r.nextInt(y - x) + x;
This is the most basic way of getting a random number in a range.
I bet there is a getMin and getMax method in the range class, so use that for x and y.
Also, if you want a random number greater than a min value of x, just do:
Random r = new Random();
Math.abs(r.nextInt().nextInt()) + x;
^The code above generates any positive integer, and the x ensures the min value.
-or-
nextInt(Integer.MAX_VALUE - (x + 1)) + (x + 1)
-as suggested by ColinD
Hope this helps.
-Classic
Like Louis says there's no built-in way to do this, but there are a couple of fairly straightforward options. Note that we have to assume all Range instances are bounded on both sides - you cannot select a random value from an unbounded or non-discrete range (e.g. (-∞..0]).
The easiest to implement solution is to simply convert the Range into a ContiguousSet, from which you can select a random value in linear time. This has the advantage of working for any discrete type, not just Range<Integer>.
public static C random(Range<C> range, DiscreteDomain<C> domain) {
Set<C> set = ContiguousSet.create(range, domain);
int index = random.nextInt(set.size());
return Iterables.get(set, index);
}
Of course constant time would be better, especially for large ranges. Canonicalizing the Range first reduces the number of cases we have to handle, and we can use the f(y-x) + x pattern JClassic suggests.
public static int random(Range<Integer> range) {
checkArgument(range.hasLowerBound() && range.hasUpperBound(),
"Cannot select a random element from unbounded range %s", range);
Range<Integer> canonical = range.canonical(DiscreteDomain.integers());
return random.nextInt(canonical.upperEndpoint() - canonical.lowerEndpoint())
+ canonical.lowerEndpoint();
}
You can extend this easily for Long with Random.nextLong() (but note that Random.nextLong() cannot return all long values, so SecureRandom would be preferable).

Random number problems

I have a bit of a complicated question. I'm currently trying to write a REALLY simple version of path finding, and to do that I need a way to generate number within a range, and each number must be different from all the others, and bigger than the last number. How would I go about doing this? So output would look like:
1,5,6,9,15,18
Create a random generator function:
public static int randInt(int min, int max) {
// Usually this can be a field rather than a method variable
Random rand = new Random();
// nextInt is normally exclusive of the top value,
// so add 1 to make it inclusive
int randomNum = rand.nextInt((max - min) + 1) + min;
return randomNum;
}
(code courtesy from an answer by Greg Case).
Call this wherever you want and check as like:
int a;
a=randInt(min,max);
and for the next time parse the previously generated value, like:
randInt(a, max);
Use reservoir sampling to pick n numbers from your range. Since you're going through the range in order the resulting list is sorted.

Random Number In A Range

I have an app I am writing for iOS and Android. On startup I am trying to get a random number between 1 and 6.
iOS (Objective-C):
int random = rand() % (6 - 1) + 1;
Android (Java):
Random random = new Random();
int num = random.nextInt(6)+1;
In both cases they return 3 every time.
From other questions I have read, people are having the same issue because they are looping through randoms and keep reinstantiating the Random object. But I just want one random number, so I am only instantiating it once.
So, how can I get either of these pieces of code to get a number 1-6 instead of just 3?
For the Objective-C part, I can tell you that you have to seed the random, like this:
srand(time(0)); // seed it using the current time
And for the Java part, the new Random() constructor automatically seeds it in the default JVM for desktop applications, but not on Android. On Android, it uses a default seed value.
Random rand = new Random(System.nanoTime());
In Objective-C, you could alternately use the recommended arc4random() function that does not need to be seeded. You would use it like this:
int random = (arc4random() % 5) + 1;
A huge benefit of this function over rand() is that is has twice the range of rand(), thus allowing for "more random" numbers.
The best solution is to use arc4random_uniform if possible, it is available in iOS 4.3 and above. It eliminates bias that is usually introduced by the mod operator.
+ (u_int32_t)randomInRangeLo:(u_int32_t)loBound toHi:(u_int32_t)hiBound {
int32_t range = hiBound - loBound + 1;
return loBound + arc4random_uniform(range);
}
Note that no seeding is necessary and it produces cryptographic quality random numbers.
Not sure about Random on Android, but in other cases, you probably want to seed the Random instance with something reasonably unique, like the system time.
Random r = new Random(System.currentTimeMillis());
I tried the Java part and it works OK for me, but you can try to instantiate Random using time as a seed:
java.util.Date d = new java.util.Date();
Random random = new Random(d.getTime());
int num = random.nextInt(6)+1;
System.out.println(num);

Selecting a random color in java

I have an iPhone version of my application which is using a bit of code for setting up colors.
((rand() % 176) * 80) / 256.0f
I am new to objective c so I can't figure out how this is working. I want to make exact copy of this for Android in Java.
In Java we usually use Random() . How am i suppose to implement this above function using Random r = Random();
In Android, I'd first initialize a variable rand = new Random(). Then I would write your expression as:
rand.nextInt(176) / 3.2f
(Note that 80 / 256.0 == 1 / 3.2.) I would only assign a value to rand once and reuse the same Random object each time I needed a new color.
After a little back-of-the-envelope work, it seems that your original code is just a fancy way of computing a random float value uniformly distributed between 0 and 55.0f. Thus, a much simpler way of doing the same thing would be:
rand.nextFloat(55)
The only disadvantage of this is that it doesn't resemble the original code very closely (although it will behave the same).
Equivalent one-liner in Java would be:
((new Random().nextInt() % 176) * 80) / 256.0f;
More about the random class on the JavaDoc
Obviously you should not create a new instance of Random each time.
Random r = new Random();
// call r.nextInt() each time you need a new random integer
double color = ((r.nextInt() % 176) * 80) / 256.0f;

Categories

Resources