Randomize numbers from a specific array without duplicates - java

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

Related

Java select from a pool of random numbers

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.

Random Number Generation in JAVA

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

storing sets of integers to check if a certain set has already been mentioned

I've come across an interesting problem which I would love to get some input on.
I have a program that generates a set of numbers (based on some predefined conditions). Each set contains up to 6 numbers that do not have to be unique with integers that ranges from 1 to 100).
I would like to somehow store every set that is created so that I can quickly check if a certain set with the exact same numbers (order doesn't matter) has previously been generated.
Speed is a priority in this case as there might be up to 100k sets stored before the program stops (maybe more, but most the time probably less)! Would anyone have any recommendations as to what data structures I should use and how I should approach this problem?
What I have currently is this:
Sort each set before storing it into a HashSet of Strings. The string is simply each number in the sorted set with some separator.
For example, the set {4, 23, 67, 67, 71} would get encoded as the string "4-23-67-67-71" and stored into the HashSet. Then for every new set generated, sort it, encode it and check if it exists in the HashSet.
Thanks!
if you break it into pieces it seems to me that
creating a set (generate 6 numbers, sort, stringify) runs in O(1)
checking if this string exists in the hashset is O(1)
inserting into the hashset is O(1)
you do this n times, which gives you O(n).
this is already optimal as you have to touch every element once anyways :)
you might run into problems depending on the range of your random numbers.
e.g. assume you generate only numbers between one and one, then there's obviously only one possible outcome ("1-1-1-1-1-1") and you'll have only collisions from there on. however, as long as the number of possible sequences is much larger than the number of elements you generate i don't see a problem.
one tip: if you know the number of generated elements beforehand it would be wise to initialize the hashset with the correct number of elements (i.e. new HashSet<String>( 100000 ) );
p.s. now with other answers popping up i'd like to note that while there may be room for improvement on a microscopic level (i.e. using language specific tricks), your overal approach can't be improved.
Create a class SetOfIntegers
Implement a hashCode() method that will generate reasonably unique hash values
Use HashMap to store your elements like put(hashValue,instance)
Use containsKey(hashValue) to check if the same hashValue already present
This way you will avoid sorting and conversion/formatting of your sets.
Just use a java.util.BitSet for each set, adding integers to the set with the set(int bitIndex) method, you don't have to sort anything, and check a HashMap for already existing BitSet before adding a new BitSet to it, it will be really very fast. Don't use sorting of value and toString for that purpose ever if speed is important.

Random Number generator to cover all numbers in the set

I am writing an Android app and I want to generate random numbers.
But, Java's RandomGenerator gives me only pseudo random numbers. The numbers repeat and not all the numbers are covered.
I want something that will give me non-repeating numbers and will cover all the numbers. How do I do that?
You can put all random values you want into a List and shuffle it.
List<Integer> numbers = ...
Collections.shuffle(numbers);
This will give you unique numbers in a random order.
You could fill a data structure with the numbers you want to loop over, then randomize the order of the elements in the structure and pull them out one by one. Alternatively, you could randomly pick indexes, and retrieve elements at those indexes. Whichever you do (you would choose the one more efficient for the specific data structure), you be sure to remove this element as you grab it. As you keep going your data structure will get smaller and smaller until you've received every element and have nothing left. This also ensures you'll never hit the same number twice, because you'll have removed it from your pool of possible numbers.

random number generation and exclusion of the generated numbers

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.

Categories

Resources