eliminating repeated random numbers [duplicate] - java

This question already has answers here:
How can I prevent the overlapping random numbers
(8 answers)
Closed 2 years ago.
I need to get the numbers 0-11 in a random order and make sure each number is only gotten once. It is still sending same numbers into my Line2 class though. How do I make sure that the int variable lineChoice is completely different every time?
My problem is the if/else is not properly making sure that I don't send an already selected lineChoice to my Line2 class.
for(int i = 0; i < 12; i++){
//get a random line choice 0-11
lineChoice = (int)(Math.random() * 11); //0-11;
//if that number was already chosen
//get a new random number and add it to the array
if(randomNumbers.contains(lineChoice)){
lineChoice = (int)(Math.random() * 11); //0-11;
randomNumbers.add(lineChoice);
}else{
//if not already in array, add to array
randomNumbers.add(lineChoice);
}
//make a Line based on the random lineChoice number
line = new Line2(lineChoice);
//add the line to the string poem
poem += "\n" + line + "\n\n\n";
}

You can create a List of Int from 1 to 11, and then randomize it.
List<Integer> ints = IntStream.range(1,12).boxed().collect(Collectors.toList());
Collections.shuffle(ints);
System.out.println(ints);

Here is the recommended way of doing it.
int [] nums = {0,1,2,3,4,5,6,7,8,9,10,11};
for (int i = nums.length-1; i >= 0; i--) {
int s = (int)(Math.random()*(i+1));
System.out.println(nums[s]); // here is where you get your number
nums[s] = nums[i];
}
or if you just want to shuffle the array.
for (int i = nums.length-1; i >= 0; i--) {
int s = (int)(Math.random()*(i+1));
int t = nums[s];
nums[s] = nums[i];
nums[i] = t;
}

You need an array to do so,
Follow the following code, you just need to generate 11 (out of 12) random numbers in total. The last number will be selected automatically.
int[] rn = new int[12];
for(int i=0; i<12; i++) rn[i]=i; // 0 to 11
Random rNumber = new Random();
int t, z;
for(int i=11; i>0; i--) {
z = rNumber.nextInt(i+1);
t = rn[i];
rn[i] = rn[z];
rn[z] = t;
}
System.out.println(Arrays.toString(rn));

Related

Duplicate entries while generating Random number [duplicate]

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+" ");

How to create an array with unique integers as elements [duplicate]

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);

Random number in array

int[] integers = new int[12];
Random r = new Random();
for (int i = 0; i < integers.length; i++) {
integers[i] = r.nextInt((10 - (-10) + 1) + (-10));
}
I'm executing it using online compiler and it throws an error at random.
can anyone help me to solve that problem? I don't know how to write that half of it be negative and half positive. And that random number can't be 0
First of all, to generate a number between -10 and 10, the correct code is :
integers[i] = r.nextInt(21)-10;
r.nextInt(21) will generate numbers between 0 and 20, so subtracting 10 will give you the desired range.
Now, you must validate the random numbers you generated, to make sure you don't generate too many positives or negative, and no zeroes.
int posCount=0;
int negCount=0;
for (int i = 0; i < integers.length; i++) {
integers[i] = r.nextInt(21)-10;
if (integers[i]>0)
posCount++;
else if (integers[i]<0)
negCount--;
if (posCount>6||negCount>6||integers[i]==0)
i--; // redo the current iteration of the loop, since the last generated
// number should be replaced
}
Another alternative, which will run faster, is to generate first 6 positive integers (r.nextInt(10)+1) and then 6 negative integers (-1-r.nextInt(10)), but I'm not sure whether the order of the generated numbers is important (i.e. is it acceptable that all the positives will come before all of the negatives).
1+ r.nextInt(10) gives integers 1-10. For negative integers, just put minus sign to the result of this calculation. Call it six times for positives and six times for negatives. What kind of error you get?
check this :
Random r = new Random();
int[] integers = new int[10];
boolean isEven=false;
int i = 0;
while(true){
int check = r.nextInt(10)*(isEven?-1:1);
if (check != 0){
isEven = !isEven;
integers[i] = check;
System.out.println(integers[i]);
i++;
}
if(i == 10){
break;
}
}
Keeping it simple:
Fill the current index with a random number from (1 to 10);
Fill the next index with a random number from (-1 to -10);
int[] integers = new int[12];
Random r = new Random();
for (int i = 0; i < integers.length; i+=2) {
integers[i] = r.nextInt(10) + 1;
if((i+1)<integers.length){
integers[i+1] = r.nextInt(10) -10;
}
}

How to return 5 random "Powerball" numbers in Java

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!

Java array counters

I am practicing using The new Boston tutorials, however there is one program that I don't fully understand. The program is designed to count the frequency of a number occuring in each dice roll and storing the results in an array. The line I have trouble with is ++freq[1+newDice.nextInt(6)]. I understand [1+newDice.nextInt(6)]; however how does the array know to increment each index by one each time the number occurs?
Random newDice = new Random ();
int freq[] = new int [7];
for(int i = 1; i<= 1000; i++)
{
++freq[1+newDice.nextInt(6)];
}
System.out.println("Dice Number\tFrequency");
for(int i = 1; i< freq.length; i++)
{
System.out.println(i+"\t\t"+freq[i]);
}
It is incrementing the value stored at that position in the array. It is not incrementing the array index.
It is equivalent to:
int index = 1+newDice.nextInt(6);
int f = freq[index];
++f;
freq[index] = f;

Categories

Resources