I have to create 15 question where only 10 will be display randomly.(10 array over 15 array). I need to make sure that there is no duplication of array during the random process.
public static void main(String() args){
String question_1 = question_One();
//to question 15
String question_15 = question_fifteen();
String [] question = new String [14];
question[0] = question_1;
question[1] = question_2;
//to question 15
question[14] = question_15;
int random = (int) (Math.random()*11);
System.out.print(question[random]);
}
I'd take the array of questions, shuffle it, and then just take the first ten questions form it. Arrays in Java are extremely limited, though, and this would be much easier to do with a proper Collection, e.g., an ArrayList:
// Build the question list:
List<String> questions = new ArrayList<>(15);
questions.add(question_1);
questions.add(question_2);
// etc...
// Shuffle it:
Collections.shuffle(questions);
// Ask the first ten:
List<String> questionsToAsk = questions.subList(0, 10);
EDIT:
The usage of ArrayLists and Collections is just a convenience. The same logic should also stand with arrays, although it will require you to implement some of it yourself:
// Build the question list:
String[] questions = new String[15];
questions[0] = question_1;
questions[1] = question_2;
// etc...
// Shuffle the first 10 elements.
// Although the elements can be taken from indexes above 10,
// there no need to continue shuffling these indexes.
Random r = new Random();
for (int i = 0; i < 10; ++i) {
int swapIndex = r.nextInt(15 - i) + i;
String temp = questions[i];
questions[i] = questions[swapIndex];
questions[swapIndex] = temp;
// Ask the first ten:
String[] questionsToAsk = new String[10];
for (int i = 0; i < 10; ++i) {
questionsToAsk[i] = questions[i];
}
Related
This question already has answers here:
Generating Unique Random Numbers in Java
(21 answers)
Closed 11 months ago.
With the below code if we try to generate random numbers from 1 to 10, I some times get duplicate values.
Below code should generate 5 unique values for random numbers between 1 to 10.
When I print the array it happens uniqueness is not guaranteed. Output was 2,1,9,10,2.
2 was repeated in this case.
Random random = new Random(System.currentTimeMillis());
random.setSeed(System.currentTimeMillis());
int[] myUniqueValues = new int[5];
for (int i = 0; i < 5; i++) {
myUniqueValues[i] = random.nextInt(10) + 1;
}
return myUniqueValues;
One way of doing this would be to create a list and pick randoms from it:
Random r = new Random();
ArrayList<Integer> list = new ArrayList<Integer>();
for(int i=0: i<10; i++){
list.add(i);
}
private int getUniqueRandom(){
int index = r.nextInt(list.size());
int number = list.get(index);
list.remove(index); // Check that it removes the Index not the value from list
return number;
}
Another way if you have a lot of numbers and dont want to store them in memory
Random r = new Random();
ArrayList<Integer> list = new ArrayList<Integer>();
for(int i=0; i<5; i++){
do{
int number = r.nextInt(10);
}while(!list.contains(number))
list.add(number);
}
The way with Set as suggested by steven7mwesigwa
This works because Sets can only contain unique values
Random r = new Random();
HashSet<Integer> list = new HashSet<Integer>();
while (list.size() < 5) {
list.add(r.nextInt(10));
}
A one liner from https://stackoverflow.com/a/31656679/11355399
int[] array = ThreadLocalRandom.current().ints(0, 10).distinct().limit(5).toArray();
We can use Set Collection here to remove duplicates inside loop itself. Set has method called contains which will check weather output of random function is already present in our result set or not. if it is present we can skip that iteration. if not we can random to our result set. please check below snippet.
Random random = new Random(System.currentTimeMillis());
random.setSeed(System.currentTimeMillis());
Set<Integer> myUniqueValues2 = new HashSet<>();
int k=0;
while(k<5) {
int test = random.nextInt(10) + 1;
if(!myUniqueValues2.contains(test)) {
myUniqueValues2.add(test);
k++;
}
}
for(int i: myUniqueValues2)
System.out.println(i+" ");
This question already has answers here:
Java Array of unique randomly generated integers
(10 answers)
Closed 5 years ago.
i want to create an array of 10000 unique random elements. Till now i only figure out how to create random integers and fill an array and finding the doubles and deleted them. But this decrease the size of the array which i dont want it.
So the question is how i can fill an array with unique integers as elements without decreasing the size of the array.
You could use this code. Usage of Set will eliminate duplicates and you are fetching random numbers until you get 10000 different random integers.
Set<Integer> numbers = new HashSet<>();
Random r = new Random();
while (numbers.size() < 10000) {
numbers.add(r.nextInt(100000));
}
Integer[] a = new Integer[numbers.size()];
a = numbers.toArray(a);
I found this great solution:
This solution doesn't need any Collection class.
public static int[] createRandomNumbers(int howMany) {
int n = howMany + 1;
int a[] = new int[n];
for (int i = 0; i < n; i++) {
a[i] = i;
}
int [] result = new int[n];
int x = n;
SecureRandom rd = new SecureRandom();
for (int i = 0; i < n; i++) {
int k = rd.nextInt(x);
result[i] = a[k];
a[k] = a[x-1];
x--;
}
return result;
}
System.out.println(Arrays.toString(createRandomNumbers(10000)));
Reference: Best way to create a list of unique random numbers in Java
Hope it helps
Try this logic:
USE AN ARRAYLIST ENTIRELY, THEN CONVERT TO AN ARRAY AT THE END OF THE ENTIRE OPERATION.
Declare an arraylist
For every random number generated, check if the number already exists in the arraylist (using the .contains() method). If it does, repeat the process, else, move to the next number.
Code example:
Arraylist<Integer> arr = new Arraylist<>();
arr.add(generate()); //I included this line so that the arraylist won't be empty
//Note that the method *generate()* generates a new random number
for(int i = 0; i < 9999; i++){
int next = generate(); //the method that generates your number
if(arr.contains(next)){
i--; //The entire operation will be repeated for this index.
}
else{
arr.add(next); //Add the number to the arraylist
}
}
int[] finalArray = arr.toArray(); //Your final resultant array!
I hope this helps.. Merry coding!
You can use Set. This Collection that contains no duplicate elements.
Documentation https://docs.oracle.com/javase/7/docs/api/java/util/Set.html
Set<Integer> numbers = new HashSet();
do {
numbers.add(ThreadLocalRandom.current().nextInt());
} while(numbers.size() < 10000);
I'm using Eclipse and I'm trying to take a string:
1 2 3 4
out of an ArrayList:
ArrayList strings = new ArrayList<>();
And store each number into a two dimensional array:
int size = (int) strings.get(0); // Represents the number of rows
int stringList[][] = new int[size][];
// Store results in a two dimensional array
for(int i = 0; i < size; i++){
int index = i + 1;
String fish = (String) strings.get(index);
Scanner npt = new Scanner(fish);
for(int j = 0; npt.hasNext(); j++) {
size[i][j] = Integer.parseInt(npt.next());
}
}
This is the section that is causing the error:
// ERROR: The type of the expression must be an array type but it resolved to int
size[i][j] = Integer.parseInt(npt.next());
strings is a raw type. Let's start by fixing that1,
List<String> strings = new ArrayList<>();
Then you can use Integer.parseInt(String) parse2 the String to an int like
int size = Intger.parseInt(strings.get(0));
Then there's no need for a cast in
String fish = (String) strings.get(index);
You can use
String fish = strings.get(index);
etc.
1 And program to the List interface.
2 Not cast.
You probably meant
stringList[i][j] = Integer.parseInt(npt.next());
though that wouldn't work either, unless you properly initialize the stringList array.
You would have to initialize stringList[i] (for each i) with something like stringList[i] = new String[someLength]; but I'm not sure which length you should use.
int[] drawNumbers = new int[10];//Array With 10 Random Numbers USED for DRAWN NUMBERS
String x = "Drawn Numbers: ";
List<Ticket> ticketWon ;
do{
//GENERATING 10 Random Numbers
for (int i = 0; i <= drawNumbers.length -1 ; i++) {
Random r = new Random();
drawNumbers[i] = r.nextInt(99) + 1;
x += drawNumbers[i] + " ";
}
}
I'm trying to generate 10 random numbers that must be random generated and Unique. My problem is that with Random r = new Random() there are times that replicated numbers are shown. How can i generate 10 random numbers from range 1 to 99 without replications?
Problem is for a Lottery System
I would like to use Collection.Shuffle but I'm not that sure how it should be implemented.
Here is an alternative way to achieve your desired result. We populate a list with values 1 to 99. Then we shuffle the list and grab the first 10 values:
public static void main(String[] args) {
ArrayList<Integer> list = new ArrayList<Integer>();
for (int i=1; i<100; i++) {
list.add(new Integer(i));
}
Collections.shuffle(list);
for (int i=0; i<10; i++) {
System.out.println(list.get(i));
}
}
You won't have to import/directly deal with Random, which is a plus. However, as pointed out by #Voicu (in the comments), shuffle does indeed utilize random:
public static void shuffle(List<?> list) {
if (r == null) {
r = new Random();
}
shuffle(list, r);
}
private static Random r;
You can broadly think of this problem as having a deck of cards numbered from 1 to 99, and you want to pick 10 of those cards. The solution would be to, programmatically, create that deck and then randomly select from that deck and remove from the deck.
We can model the deck as a List of Integers and populate that List with entries from 1 to 99 with something like this:
List<Integer> deck = new ArrayList<Integer>();
for( int i=1; i<=99; i++ ){
deck.add( i );
}
We then need to pick a random card between the 0th card (lists are numbered starting at 0) and the number of elements in the list:
int draw = r.nextRandom( deck.size() );
Integer card = deck.remove( draw );
And repeat that 10 times, doing something with the "card" (say, putting it into an array, or another list, or whatever:
int drawNumbers = new int[10];
for( int co=0; co<10; co++ ){
int draw = r.nextRandom( deck.size() );
Integer card = deck.remove( draw );
drawNumbers[co] = card;
}
Use Set<Integer>.
Set<Integer> set = new HashSet<Integer>();
int[] drawNumbers = new int[10];
Random r = new Random();
for(int i=0; i<10; i++)
{
drawNumbers[i] = r.nextInt(99) + 1;
while(set.contains(drawNumbers[i]))
drawNumbers[i] = r.nextInt(99) + 1;
set.add(drawNumbers[i]);
}
I'd generate random numbers and save them to a Set until I get 10 numbers. Then create a list from it, shuffle it, and then take numbers from it.
final int NUMBERS_TO_DRAW = 10;
Random r = new Random();
// Generate NUMBERS_TO_DRAW random numbers
Set<Integer> randoms = new HashSet<>();
while (randoms.size() < NUMBERS_TO_DRAW) {
randoms.add(r.nextInt(99) + 1);
}
// Now shuffle them:
List<Integer> shuffledRandom = new ArrayList<>(randoms);
Collections.shuffle(shuffledRandom);
EDIT:
As #MarkPeters noted in the comments, using a LinkedHashSet would eliminate the need to shuffle:
final int NUMBERS_TO_DRAW = 10;
Random r = new Random();
// Generate NUMBERS_TO_DRAW random numbers
LinkedHashSet<Integer> randoms = new LinkedHashSet<>();
while (randoms.size() < NUMBERS_TO_DRAW) {
randoms.add(r.nextInt(99) + 1);
}
It would be easier to use a list so you could check if it already contains the number and re-generate if it does.
List<Integer> drawNumbers = new ArrayList<Integer>();
Random r = new Random();
int newNumber = -1;
do
{
newNumber = r.nextInt(99) + 1;
} while(drawNumbers.contains(newNumber); //Make sure the number is not already in the list.
Then put this in a loop to repeat 10 times.
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.
Simply place each random number into an array and return the array...
public int[] powerBalls() {
int[] balls = new int[5];
for (int index = 0; index < 5; index++) {
balls[index] = (int) (Math.random() * 42) + 1;
}
return balls;
}
You can use the Set to generate 5 Unique Random numbers.
Random random = new Random();
Set randomNumbers = new HashSet<Integer>();
while(randomNumbers.size()< 5) {
randomNumbers.add(random.nextInt(42)+1);
}
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 in randomNumbers set to your ArrayList.
Update:-
To suit your needs, you need to do something like this:-
Random random = new Random();
Set<String> set = new HashSet<String>();
while(set.size()< 5) {
set.add(String.valueOf(random.nextInt(42)+1));
}
fortuneList3.addAll(set);
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:
public int[] powerBalls() {
// create array with all numbers
List<Integer> balls = new ArrayList<Integer>(42);
for (int i = 1; i <= 42; i++)
balls.add(i);
// shuffle
Collections.shuffle(balls);
// take first 5
int[] result = new int[5];
for (int i = 0; i < 5; i++)
result[i] = balls.get(i);
return result;
}
Try it like this:
IntArray = new int[5]; //Create an array
for (int i = 0; i < 5; i++) {
IntArray[i] = (int) (Math.random() * 42 + 1);
}
Store the numbers in array and return that array.
int []randArray;
randArray = new int[5];
for (int i = 0; i < 5; i++) { //for 5 random numbers
randArray[i] = (int) (Math.random() * 42 + 1);
}
//now return this array "randArray"
It's a straight forward approach.
List<Integer> generated = new ArrayList<Integer>();
for (int i = 0; i < 5; i++)
{
while(true)
{
int r = (int) (Math.random() * 42 + 1);
if (!generated.contains(r))
{
generated.add(r);
break;
}
}
}
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
function getNumbers() {
var a=[]; // array to return
for(i=1;5>=i;i++){ // for loop to get first 5 numbers
var b = Math.floor(Math.random()*59)+1; // set #
while (a.indexOf(b) > -1) { b = Math.floor(Math.random()*59)+1; } // reset # if already used
a.push(b); // add number to array
}
a.push(Math.floor(35*Math.random())+1); // add ball 6 number
return a; // 0 index array will have a length of 6, [0-4] being whiteball numbers, [5] being the red ball
}
The Plugin
jsFiddle
Contains the plugin between comment lines
Shows example use
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.
Style: a note!
All styling is done through a style tag added to the header upon initialization. This means there's no need for extra files to add, but it also gives the ease of custom styling. See more about styling in the jsFiddle!