Is it possible to do this in Java ? I want to generate a random number such that given a range say for example: between 1 and 70 - everytime the random number is generated it should be excluded from generation results.
so [1,70] rand = 56 (now 56 shouldn't be considered next time)
[1,70] = 63 (now 56,63 should be excluded from generation till my code runs)
This is equivalent to shuffling an array of numbers containing [1..70] and then dealing them out one at a time. Look up "shuffle algorithm" on Google. Here's a link http://www.vogella.de/articles/JavaAlgorithmsShuffle/article.html
I asked the same question here: How can I generate a random number within a range but exclude some?
The general strategy is something like filling an array with 70 values. Just remove the values that you randomly generate as per the link above.
you could populate the range into an array and shuffle the array. This would be inefficient though for very large ranges
Another trivial alternative, using HashMaps to keep track of random numbers.
It is sort of quick and dirty.
HashMap<Integer,Integer> hmRandomNum = new HashMap<Integer,Integer>();
Integer a = < generate random number>
if( hmRandomNum.get(a) == null)
{
hmRandomNum.put(a,a);
}
else
{
// ignore this random number. this was already selected and present in the hashmap.
}
//Iterate depending on how many numbers you want.
Related
This question already has answers here:
Picking a random element from a set
(34 answers)
Closed 2 years ago.
I'm working on a problem in which I need to pull a random String from a keySet. Just wondering if anyone can give me some direction here. I'm pretty lost on it. I've found quite a few ways to do it if I were using an int, but not a String. For example I want to quiz a user on States and their Capitals, and to pull out a random Key from the keySet for the question.
Here's the set:
Set<String> states = stateCapitals.keySet();
Set is not the best data structure for random indexing.
Better convert to a List and use a random generator to select an index. If you really need to stay with a Set, you can generate a random index n and iterate through the Set, stop at the nth element. For selecting multiple elements, there is no benefit of working with a List. Any iterable would be fine.
The key idea is to dynamically adjust selection probability so you can choose m (out of sizeof(Set)): In the easiest example of m=1, select 1st element with probability of 1/N, if you didn't select it, select 2nd element with probability 1/(N-1)..and so on.
Use conditional probability to show all elements are selected under a fair chance 1/N.
A keySet similar to HashSet is un-ordered and thus makes no guarantee to the order of the element in the set. So pulling a random string might not be as effective thing to do from a set.
Convert the set into arrays or list and then performing random string gets might be good solution.
String ranKey = map.keySet().toArray()[new Random().nextInt(map.keySet().size())].toString();
Try this code
onPress: function () {
debugger;
var textArray = ['Pritesh', 'Nimesh', 'Harshil', 'Ravi', 'Amit', 'Brijesh'];
var randomNumber = Math.floor(Math.random() * textArray.length);
for (var i = 0; i < textArray.length; i++) {
if (i === randomNumber) {
console.log(textArray[i]);
}
}
ArrayList<States> statesList = new ArrayList<>( states );
State x = statesList.get( (int)(statesList.size() * Math.random()) );
The code above will get what you want but this could be inefficient if it's a very large list.
I have a array shuffled with some numbers I want to randomize the numbers in shuffled array without duplication am using below code
int shuffled array [] = {1,3,5,7,8}
Random random = new Random();
int random =shuffled array[random.nextInt(shuffled array.length)];
I am getting duplicate values.
How do I get to generate random number without any duplicate values?
In general you can do in of the following:
Create random numbers and keep them in a Set so that they are unique and keep pooling them until the desired amount of random numbers is achieved.
If you have a pool by which you want to pool numbers you can create an array (as you do) and then shuffle this array. Why this solution does not work for you? I think you are mixing the 2 solution and get duplicates.
Edit:
About efficiency (if you are concerned about it):
The first method uses a pseudorandom generator to produce the unique numbers. As the number of unique number in respect to the total possible numbers increases, (e.g. if you have an array and want all element to be picked up at random) then this approach might be inappropriate. If on the other hand you just want to pick 10 unique random numbers it is possibly efficient enough.
The shuffle approach as states This method runs in linear time so it should be preferred in this case (yours that is).
int pos =shuffled array[random.nextInt(4)]
int random_num_from_shuffled_array = shuffled array[pos];
Create a Collection (Set - because of the no-duplicates requirement) using your array.
Use Collections.shuffle(mySet);
You are actually using the Random class and nextInt which do not guarantee uniqueness of consecutive elements!
I guess what you need is achieved by Collections.shuffle. See the documentation
ArrayList<ArrayList<ArrayList<String>>> one = new ArrayList<ArrayList<ArrayList<String>>>();
one would look something like this with some example values:
[
[
["A","B","C",...],
["G","E","J",...],
...
],
[
["1","2",...],
["8","5","12","7",...],
...
],
...
]
Assuming that there will always be one base case, at least one letter arraylist (e.g. ["A","B","C"]), but there could be more (e.g. ["X,"Y","Z"]) and there may be any size of number arraylists, maybe none at all, but could be hundreds (e.g. ["1","2","3"],...,["997","998","999"]). Also, there could be more types of arraylists (e.g. ["#","#","$"]) of any size. So really the only thing that is definitive is that ALWAYS:
one.size()>=1
one.get(0).size()>=1
one.get(0).get(0).size()>=1
So the problem is: How can I best get every combination of each category without knowing how large each arraylist will be or having any repeats but assuming that one.get(0).get(0) is valid? e.g. ["A","B","C",...] ["1","2",...] ..., ["A","B","C",...] ["8","5","12","7",...] .... I'm using Java in my project currently but an any algorithm that works I can convert over myself. I apologize if this is not clear, I'm having a hard time putting it into words which is probably part of why I can't think of a solution.
I know two solutions to this, the recursive and the non recursive. Here's the non recursive (similar to the answer at How to get 2D array possible combinations )
1) Multiply the length of every array together. This is the number of possible combinations you can make. Call this totalcombinations.
2) Set up an int[] array called counters. It should be as long as the number of arrays, and all initialized to 0.
3a) For totalcombinations times, concatenate counter[0]th entry in arrays[0], the counter[1]th entry in arrays[1]... etc and add it to the list of all results.
3b) Then set j = 0 and increment counters[j]. If this causes counters[j] > arrays[j].length, then counters[j] = 0, ++j and increment the new counters[j] (e.g. repeat 3b)) until you do not get such an overflow.
If you imagine counters as being like the tumblers of a suitcase - when you overflow the first digit from 9 to 0, the next one ticks over - then you should get the strategy here.
I'm making a bingo like program in java, I was wondering if it was a ll possible to select a number from a pool, then have it cross it out. I was thinking of putting the 75 (bingo numbers) into an array then have it select it from there, but i cant seem to find a way to get rid of that number once it's selected. for example, i only want to call the number 55 ONCE, then have it gone, or non-accessible from the pool once it's called by my random function.
Thanks
Rob
Generate array 1..75.
Shuffle.
Read one at the time.
http://docs.oracle.com/javase/1.4.2/docs/api/java/util/Collections.html#shuffle%28java.util.List%29
(deleted my previous answer because I misread the question)
Easiest way I can think of to do this is to store them in an ArrayList, track the size and feed that into a random number generator to randomly access an index and remove after use.
Place all 75 numbers into an array.
Call Arrays.shuffle() on the array.
Read the array in-order.
Create a Collection of Integers
Randomly generate an int with a range from zero to collection.size()-1
Remove the item at the index of the random int from step 2. This item is the number you call and will no longer be selectable.
I know about the JAVA Random class and its use. But I want to generate a random number which should not be repeated until all the numbers in the range are generated at least once. Can anybody provide me some reference..?
While using the Random class, the problem I face is that some numbers get repeated 2 or 3 times while some are not generated at all.. My application may fail in this scenario as I have another thread processing some requests based on the numbers getting generated....and the moment there is a delay and next unique digit is not available, it stops without processing the non - generated numbers...
You can generate all the values in range and shuffle them. Collections.shuffle() Once you have uses every value, repeat.
Imagine you have decks of cards, You take one deck which has a every card once, you shuffle it and you will know what while each card will come in a random order, only once. When one deck has finished you take all the cards again and reshuffle (or a new deck and shuffle that)
Create a List with all the possible random numbers in the range.
Instead of using a random number as result, use a random integer to pick an index in the list
remove it from the list and return it.
Take care to adjust the range of random integer to the current list size (it will decrease by one each time you get a new number)
you can keep a list with you of all the numbers that are already picked out and check if the new random number is in that list or not
Here is an example of someone who asked the same question