Trying to return 5 random numbers between 1 and 42 in Java.
I currently have logic to return a single number (putting it into an ArrayList, but I'd like to do away with that.) I'm stumped on implementation to return 5 random numbers. Would I need 5 for loops?
for (int i = 0; i < 10; i++) {
int r = (int) (Math.random() * 42 + 1);
}
I've seen some other related examples here and they seem more complex than what my needs dictate. However, I could be wrong.
Store the numbers in array and return that array.
Just throwing my 2 cents in. I recently made a jQuery Plugin, appropriately named "Powerball". I'll share with ya the formula i'm using as well as link ya my plugin. Not sure why anyone would really need this. I did it just for fun! LoL!
The Function
The Plugin
jsFiddle
Use is as easy as
$("element").powerball()
. However, only one method exist for it at the moment,$("element").powerball("setNumbers")
. That method simply resets the numbers shown in the p tags.Try it like this:
Simply place each random number into an array and return the array...
Be careful! Each number can be taken only one time. With your solution it is possible to get same number more than one time.
Other solution (and here you can't have same numer more than one time) is to create array with all numbers, shuffle it and take first 5:
You can use the
Set
to generate5
Unique Random numbers.Since you've mentioned that you're using an
ArrayList
which will hold all the random numbers, you could just add all the elements present inrandomNumbers
set to yourArrayList
.Update:-
To suit your needs, you need to do something like this:-