generating random numbers without duplicates in java [duplicate] - java

This question already has answers here:
Creating random numbers with no duplicates
(20 answers)
Closed 7 years ago.
So I am generating random coordinates on a given grid that contains x number of rows and y number of columns. Let's say I want to generate 25 random numbers on a 8 by 6 grid.(8 columns, 6 rows)
I wrote piece of code like this and it is only partially working because this code does not excludes duplicates:
int intputRows =6;
int inputColumns=8;
Random randomNumGenerator = new Random();
for(int i=0;i<25;i++){
int randomRows = randomNumGenerator.nextInt(inputRows);
int randomColumns = randomNumGenerator.nextInt(inputColumns);
}
My question is, how do I avoid to generate duplicate numbers? I understand there are ways like put those in a List structure and shuffle, but could I done it with Random generator?

Just use a Set:
int intputRows =6;
int inputColumns=8;
HashSet<Integer> set = new HashSet<>();
Random randomNumGenerator = new Random();
int temp;
for(int i=0;i<25;i++){
temp = randomNumGenerator.nextInt(inputRows);
if(set.add(temp))
int randomRows = temp;
temp = randomNumGenerator.nextInt(inputRows);
if(set.add(temp))
int randomColumns = temp;
}
You still have to implement an else, in case it already exists, but I just gave you the idea.

Simple add the numbers to a Set, for example a HashSet, which cannot contain duplicate values, until your Set hat the desired length.
Set<Integer> randomNumbers = new HashSet<Integer>();
while(randomNumbers.size() < 25) {
randomNumbers.add( randomNumGenerator.nextInt(inputRows) );
}
Of course some checks would be nice to test that there is a chance that the code will finish, etc.

Related

Adding a range of numbers to a Java array [duplicate]

This question already has answers here:
How can I generate a list or array of sequential integers in Java?
(9 answers)
Closed 5 years ago.
I am relatively new to Java programming and am trying to create an array with values from (2017 - 3017).
I was wondering if there is a way to create an array and have it pre-filled with these values so instead of doing:
int[] anArray = {2017, 2018, 2019, 2020... 3017}
which seems extremely long-winded, I can simply define a range of integers I wish to add to the array.
I know there are similar question to this one on the site, however none of them have answers that help me.
Thanks!
Edit: I forgot to mention I am using Java 7 and therefore cannot use IntStream.
How about this:
int[] anArray = IntStream.rangeClosed(2017, 3017).toArray(); //closed includes upper bound
Java 7 would simply require a loop to fill the array:
int min = 2017, max = 3017;
int count = max - min + 1; //we're including upper bound
int[] anArray = new int[count];
for (int i = 0; i < count; i++, min++) {
anArray[i] = min; //reused and incremented min
}
Well it is answered. But just to point out another way in java .. you can count the number of integers that will be coming and use iterator to fill the array.Let me know if you have any doubts in this In short I am saying to do like the following:
int arr[] = new int[1001];
for(int i=2017;i<=3017;i++){
arr[i-2017]=i;
}

Generating specific number in a random way in Java [duplicate]

I got a pool of numbers (for example {3,6,7,11,20}) and i need each number to appear in my collection x times.
My solution was to create a class, let's call it "element", of two integers (num,numOfAppearnces).
I created a pool of "elements" in arrayList, and then generated a random numbers between 0 to list.size, and got the number stored in the random index.
when numOfAppearances decreased to 0, i deleted this element from the list.
my question is, is there any other elegant solution to generate random number, not from a range?
Yes, there are shorter ways to achieve what you describe.
For example :
Integer[] arr = {3,6,7,11,20};
List<Integer> shuffled = new ArrayList<>();
for (Integer i : arr)
shuffled.addAll (Collections.nCopies(x,i)); // add i to your List x times
Collections.shuffle(shuffled); // shuffle the List to get random order
Or (if you don't want to use Collections.nCopies(x,i)) :
Integer[] arr = {3,6,7,11,20};
List<Integer> shuffled = new ArrayList<>();
for (int j = 0; j < x; j++)
for (Integer i : arr)
shuffled.add (i);
Collections.shuffle(shuffled); // shuffle the List to get random order
here is simple Python program
import random
def genRNum():
numlist = [3,6,7,11,20]
i = random.randrange(0,4)
RNum = numlist[i]
print(RNum)
genRNum()
Another Easiest way is to use Windows PowerShell
Get-Random 3,6,7,11,20
That't it

How to generate a random number in java with array bounds?

I want to ask how to generate a random number in java , i know it is done by random.nextint() but i want to check if the number is not what i wanted then it should be rejected and a new random number should be generated .
I want something like this :
Integer[] in = {1,2,3,4,5};
int a = new Random().nextInt(10);
for(int i=0;i<in.length ;i++)
if(a==in[i])
//new random number
if the number is present in the above array (in) then new random number should be generated
Just put it in a do-while loop:
int a;
do {
a = new Random().nextInt(10);
} while (Arrays.asList(in).contains(a));
I would avoid not generating a number you didn't want in the first place.
You can do either
int a = random.nextInt(5);
if (a > 0) a += 5;
or use a selection
int[] valid = { 0, 6, 7, 8, 9 }; // 0 to 9 but not 1,2,3,4,5
int a = valid[random.nextInt(valid.length)];
Simply call the method again. That is, if the number generated fits the if criteria then call a = new Random().nextInt(10);
Or, if your for loop ever regenerates a random number, you could just have the if statement do nothing ex: if(xyz){}; which of course would be pointless, and I think the original solution is probably what you seek.
To avoid any loops and retrying, try this:
int [] in = {1,2,3,4,5};
// generate integers from 0 up to the size of your array of allowed numbers:
int index = new Random().nextInt(in.length);
int a = in[index]; // use the random integer as index for your array of allowed numbers

How can I sort an amount of randomly generated numbers defined by the user in Java?

Hey there Stack Overflow community, so I'm still new to Java but I am trying to learn how to sort. Right now my program creates n amount of random numbers from a range of 1 - 10. Although how I would go about putting these numbers into an array to be sorted, I'm not too sure on. Should i go about doing a bubble sort instead of Arrays.sort?
Here's my code
public static final void main(String aArgs){
//User inputs a number for the amount of random numbers to generate
String UserNumbers = JOptionPane.showInputDialog("How many numbers would you like to generate?");
//The unknown amount of numbers "n" is converted from the "UserNumbers" String to an int
int n = Integer.parseInt(UserNumbers);
//Random number generator generating the amount of numbers as defined by the user
Random randomGenerator = new Random();
for (int idx = 1; idx <= n; ++idx){
int randomInts = randomGenerator.nextInt(10);
//Now to create an array for the random numbers to be put into so they can be sorted
int ArrayToSort[] = new int[n];
ArrayToSort[0] = randomInts;
Arrays.sort(ArrayToSort);
System.out.println(ArrayToSort);
}
}
}
I suspect you are not asking whether to use bubble sort because it's faster/slower then Arrays.sort but instead as Arrays.sort doesn't work for you.
I think this is due to the fact your not putting the random numbers you generated into the array you sort
Instead, try this code:
public static final void main(String args){
//User inputs a number for the amount of random numbers to generate
String userNumbers = JOptionPane.showInputDialog("How many numbers would you like to generate?");
//The unknown amount of numbers "n" is converted from the "userNumbers" String to an int
int n = Integer.parseInt(userNumbers);
//Random number generator generating the amount of numbers as defined by the user
int arrayToSort[] = new int[n];
Random randomGenerator = new Random();
for (int idx = 0; idx < n; ++idx){
arrayToSort[idx] = randomGenerator.nextInt(10);
}
Arrays.sort(arrayToSort);
System.out.println(arrayToSort);
}
The problem with your code is that you are trying to populate an array of size n with random numbers, sort it and then print it, but your code generates in each iteration a random number, allocated an n sized array, put's the random number in slot 0 of the array and sort it, and print it (doint this n times) - which won't get the same effect ofcourse
BTW, Random.nextInt(10) return a random number between 0 and 9, not 1 and 10. to achieve what you want you will need to add 1 to that random value
Arrays.java 's sort method uses quicksort for arrays of primitives and merge sort for arrays of objects. I believe that most of time quicksort is faster than merge sort and costs less memory.
Source: Why does Java's Arrays.sort method use two different sorting algorithms for different types?

Select a random int that doesn't exist [duplicate]

This question already has answers here:
Generating Unique Random Numbers in Java
(21 answers)
Closed 8 years ago.
I am doing something where I have to choose a couple random numbers, without choosing the same number again. I have tried many ways, but they will not work. I checked if the random number exists in my int[], and reset the int to another random, but what is that other random also exists, I tried fixing that but I ran into problems.
Here's my current code:
p.sendMessage("debug over max");
Random r = new Random();
for (int i=0;i<max + 1;i++) {
int ran = r.nextInt(arenaAmount);
if (ran == 0) ran = 1;
arenas[i] = ran;
}
Thats what I have so far,
so how can I make sure it doesn't have the same number. If there is another thread already please link me to it.
Thanks, Joey.
A simple solution would be to add the already generated numbers to a Set and generate random numbers until you hit one that isn't already in that Set.
But that's probably not a very good solution, check the accepted answer here for a thorough explanation.
As mentioned by Giovanni Botta in the comments, here's another simple solution that's probably better than the Set based one.
make a arenas a Set
Random r = new Random();
int ran = r.nextInt();
while( ! arenas.add(ran) ) {
ran = r.nextInt();
}
add will fail on an attempted re-entry of a value.
You could create a list of integers from 1 to maxValue, shuffle it and get the numElements first elements:
List<Integer> shuffledList(int maxValue, int numElements) {
if (numElements >= maxValue) {
throw new IllegalArgumentException("The number of elements in the list must be less than maxValue.");
}
List<Integer> numbers = range(1, maxValue);
Collections.shuffle(numbers);
return numbers.subList(0, numElements);
}
List<Integer> range(int from, int to) {
List<Integer> numbers = new ArrayList<>(to - from);
for (int i = from; i < to; i++) {
numbers.add(i);
}
return numbers;
}
This way, you are sure to get different numbers without the Set overhead. Making a call like shuffledList(10, 5) would, for example, return a list like [8, 7, 5, 1, 2], with 5 elements, where the smallest possible element is 1 and the greatest possible element is 9.
Also, if you are using Java 8 you can discard the range function and do this instead:
List<Integer> numbers = IntStream.range(1, maxValue)
.boxed()
.collect(Collectors.toList());

Categories