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
Related
The logic I applied was:
Looping though the given array and keeping the count of number of even and odd numbers in array.
Suppose "n" is number of even numbers and "m" is number of odd numbers in the array.
After that making two arrays of size "n" and "m" and storing even and odd numbers in those array and displaying both arrays.
Is this logic right? Because I'm having problem in writing code. If anyone can help.
If you can’t use ArrayList (presumably homework), then use LinkedList instead!
List<Integer> odds = new LinkedList<>();
List<Integer> evens = new LinkedList<>();
for (int i = 0; i < array.length; i++) {
if (array[i] % 2 == 0) {
evens.add(array[i]);
} else {
odds.add(array[i]);
}
}
Then print the contents of the lists as you like.
I'm trying to put a certain amount of integers into an array in random spots without putting them in the same place.
My combine method concatenates two given integers and returns the Int.
Places is an arrayList to keep the locations of the integers already put into the array.
The random method returns a random integer in between the two given ints.
The combine method works and so does the random method, but I'm not sure why it isn't working.
public void fillOne(int b)
{
for(int x = 0; x < b; x++)
{
int kachow = random(0, 5);
int kachigga = random(0, 5);
int skrrt = combine(kachow, kachigga);
if(notInArray(skrrt))
{
locations[kachow][kachigga] = 1;
places.add(skrrt);
}
}
}
You haven't really explained what isn't working. But an obvious flaw in your algorithm is that it isn't guaranteed to set b elements to 1. If your algorithm generates a duplicate position then it will set fewer than b elements.
Your logic for storing the combined positions is overly complex. One solution would be to reverse the logic: generate a single integer representing both dimensions then divide it into two when you are setting the location. That makes the checks a lot simpler.
For example, if your array is 5x5:
Set<Integer> positions = new HashSet<>();
while (positions.size() < n)
positions.add(random.nextInt(25));
for (int p: positions)
locations[p/5][p%5] = 1;
Because positions is a set it automatically excludes duplicates which means the code will keep adding random positions until their are n distinct positions in the set.
Even simpler, if you are using Java 8:
random.ints(0, 25)
.distinct().limit(n)
.forEach(p -> locations[p/5][p%5] = 1);
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
I'm making a program of the Card game War and I need the cards to not reappear so I used an Array list. I'm having trouble with this array list as it's supposed to be random and remove the number, but I get the error IndexOutOfBoundsException: Index 0, Size 0
List<Integer> values = new ArrayList<Integer>();
Random random = new Random();
Integer rand = random.nextInt(values.size()+1);
Integer cardId = values.get(rand);
values.remove(rand);
First add your Card(s) to your values List (e.g. probably not Integer).
What I'm saying is this, you need a deck of cards before you can play.
Your list is empty and you're
1) Trying to retrieve a value
2) Trying to remove a value
Which throws an error because the list is empty.
Sidenote: you can define rand and cardId as int, instead of Integer. Autoboxing/unboxing will take care of that for you.
Add values to your list and it will work as expected (and if you change random.nextInt(values.size()+1) to random.nextInt(values.size())).
You get this error because you try to access index 0 of an empty array, as it says. You cannot do this.
Your code has multiple issues.
You are not actually storing anything in values.
The acceptable range of indexes for .get() is 0 to size-1. The return range of random.nextInt(size+1) is 0 to size. This can produce out of range index values. Array indexes start at 0.
Provide the code for the values in the array...Or add values in the array.
You need to first give the List values before you can get values
List<Integer> values = new ArrayList<Integer>();
Random random = new Random();
Integer rand = random.nextInt(values.size()+1);
Try this to put values
for (int i = 1; i <= 52; i++){
values.add(i);
}
Integer rand = random.nextInt(values.size() + 1);
I simply need to know what i should do to make so that a basic array is filled with randomly generated numbers. now i know how to do that, what i don't know how to to do is to make it so that the randomly generated numbers are bigger than the last number generated all the way through to the end of the array.
Just generate for the list, and then sort them smallest to largest.
for(int i = 0; i < arr.length; ++i) {
arr[i] = Random.nextInt(100);
}
Arrays.sort(arr);
Generate random numbers, and then sort the array.
You can sort the array using Arrays.sort()
It doesn't make sure that each number is strictly bigger then the previous numbers [it only gurantees <=], so if it is an issue - you will have to make sure you have no dupes in the generated numbers.
You can generate an array of random numbers, and then sort it using Array sort.
There was a comment on the question, I lost the author's name, that recommended adding the randomly generated number to the previous number, which I thought was an interesting approach.
arr[0] = Random.nextInt(100);
for(int i = 1; i < arr.length; ++i) {
arr[i] = arr[i-1] + Random.nextInt(100);
}
This removes the need to sort your result array.
You can have your own algorithm of generating incremental...
For example...
Random each time and add that number to the last one :)
Random class in java does not allow you to have a minim limit where to start.. only one...
For example:
myArray[0] = Random.nextInt(10000);
for(int i=1; i<myArray.length; i++)
{
myArray[i] = myArray[i-1]+Random.nextInt(10000);
}
So.. it's random and you don't have to sort it.. try keeping everything simple...
I'm surprised no one mentioned that we can use SecureRandom API to easily generate random arrays without manually populating it.
For ex. generating a random array of size 100:
SecureRandom random = new SecureRandom();
int arr[] = random.ints(100).toArray();
BTW this should be possible from java 8 onwards.