I have created a random number generator and I also have an array of 30 items, however I require it to use the numbers generated to get the positions of the items in the array and display it. Sorry if I don't make much sense, I'm still trying to understand it myself!
Here's my random number generator code!
public void passRndNum() throws IOException
ArrayList <Integer> aNumber = new ArrayList <Integer>();
for (int i = 0; i < 29; i++)
{
aNumber.add(new Integer(i));
}
Collections.shuffle(aNumber);
for (int i = 0;i < 2 ; i++)
{
aPlayer[i].receiveCard(aNumber.get(i));
}
}
Is it possible to create random number between 0 and 29
Yes.
Random rnd = new Random();
rnd.nextInt(30);
to represent a counter
Yes.
int counter = rnd.nextInt(30);
of an array of 30 items
Yes, you can have an array of 30 items. Lets call it ... myArray.
and then call that counter and item to the display?
Yes.
System.out.println(counter + ": " + myArray[counter]);
Related
I got the 2d array to print but with all zero's and the only random number comes up on the bottom right corner
How do I get the code to print random numbers in all the elements of the 2d array?
Here is my code:
public static void main(String[] args) {
int columns = 8;
int rows = 4;
int rLow = 2;
int rHigh = 9;
printRandos(columns, rows, rLow, rHigh);
}
public static void printRandos(int clmn, int rws, int rlow, int rhigh) {
Random rando = new Random();
int randoNum = rlow + rando.nextInt(rhigh);
int[][] randoArray = new int[rws][clmn];
for (int i = 0; i < rws; i++) {
for (int k = 0; k < clmn; k++) {
randoArray[rws - 1][clmn - 1] = randoNum;
System.out.print(randoArray[i][k] + " ");
}
System.out.print("\n");
}
}
for (int i = 0; i < rws; i++)
{
for (int k = 0; k < clmn; k++)
{
int randoNum = rlow + rando.nextInt(rhigh);
randoArray[i][k] = randoNum;
System.out.print(randoArray[i][k]+" ");
}
System.out.print("\n");
}
your mistake inside the inner for loop of the printRandos method. Firstly your random number is outside the loop so your array elements were receiving the same number all the time. Another mistake is that you are assigning the value to the same array element all the time i.e rws-1 and clmn-1 .
inside your inner loop replace it with this:
int randoNum = rlow + rando.nextInt(rhigh);
randoArray[i][k] = randoNum;
System.out.print(randoArray[i][k]+" ");
Your bug is in this line:
randoArray[rws-1][clmn-1] = randoNum;
This stores your random number into randoArray[rws-1][clmn-1] each time, which as you noticed, is the bottom right corner. rws is always 4, and clmn is always 8. So you store the same number there 32 times, which gives the same result as storing it only once.
In the following line you are correctly printing the number from the current array location:
System.out.print(randoArray[i][k]+" ");
An int array comes initialized with all zeroes, and since except for the last corner you have not filled anything into your array, 0 is printed.
Also if you want different random numbers in all the cells, you would need to call rando.nextInt() inside your innermost for loop.
Unless you need this 2-D array for some purpose (which doesn't show from the minimal example code that you have posted), you do not need it for printing a matrix of random numbers, i.e., you may just print the numbers form within your loop without putting them into the array first.
Finally if rhigh should be the highest possible random number in the array, you should use rando.nextInt(rhigh - rlow + 1). With rlow equal to 2 and rhigh equal to 9 this will give numbers in the range from 0 inclusive to 9 - 2 + 1 = 8 exclusive, which means that after adding to rlow = 2 you will get a number in the range from 2 to 10 exclusive, in other words, to 9 inclusive.
I am on purpose leaving to yourself to fix your code based on my comments. I believe your learning will benefit more from working it out yourself.
Your assign the array value outside the array length
int[][] randoArray = new int[rws][clmn];
randoArray[rws][clmn] = randoNum;
Here randoArray[rws] is out of bounds.
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);
I have tried to program a random number generator that doesn't generate the same random number more than once. But I am unable to and can't figure out why. My code is like this at the moment:
public void printNS(){
System.out.print("Numeros Numeros: ");
for(int i=0; i < 5 ; i++){
System.out.print( (int)(Math.random()*50) + ",");
}
System.out.print("; Numeros Stars: ");
for(int i=0; i < 2 ; i++){
System.out.print( (int)(Math.random()*12)+ ",");
}
}
in java 8 you can do the following
int[] rand = new Random().ints(start, end).distinct().limit(number).toArray();
for more details/options see the doc
And before java 8 you can use a Set. Generate the random numbers until your set size is less than the desired number of random numbers
So you want k distinct random numbers from 0 to n (with k < n).
Two possible approaches:
Pick k random numbers, as you already did, and store them in a data structure. Everytime you pick a number, check if it is already contained in the structure: if it is, keep picking until you have a "new" random number. It is a simple enough approach but the loop could potentially block your application. I suggest to use a Set since it stores distinct elements by definition
Set<Integer> set = new LinkedHashSet<>(); // unordered
while (set.size() < k){
set.add((int)(Math.random()*n));
}
System.out.println(set);
Create a List and initialize it with every number between 0 and n. Then shuffle it. First k elements of the list are the numbers you want.
List<Integer> list = new ArrayList<>(n);
for (int i = 0; i < n; i++){
list.add(i);
}
Collections.shuffle(list);
list.subList(0, k).clear();
System.out.println(list);
I would suggest the second approach as it is more clean, I don't know your efficiency requirements though.
Here:
private printStars(int loops, int factor) {
for(int i=0; i < loops ; i++){
System.out.print( (int)(Math.random()*factor) + ",");
}
And now:
public void printNS(){
System.out.print("Numeros Numeros: ");
printStars(5, 50);
System.out.print("; Numeros Stars: ");
printStars(2, 12);
Hope that helps. The key point is: when you have repeating code, look at those elements that are "identical"; and then move them into another method!
I tried to generate a sorted list of random data with no duplicates in descending order for my array. It also returns number of duplicates, but it keeps printing out nothing but zero .... Can anyone help me please :(
// 2. Ask the user for size of arbitrary numbers.
System.out.print("Please enter a size for arbitray numbers: ");
int size = indata.nextInt();
int [] SortedNumbers = new int [size];
// 3. Process arbitrary numbers and remove all duplicates
int numDuplicates = generate_data(SortedNumbers);
// 4. Print the numbers and number of duplicates
printArray(SortedNumbers, numDuplicates);
and here is the random method
public static int generate_data (int [ ] list){
int duplicates = 0;
Random random = new Random();
System.out.println(n[random.nextInt(n.length)]);
return duplicates;
}
here is the print_array method
public static void printArray(int [] list, int duplicates) {
// Additional code required
System.out.println("\nSize of array: " + list.length + " .Numbers of duplicates: " + duplicates); for (int i = 0; i<list.length; i++){
System.out.printf("%7d", list[i]);
if ((i + 1) % 10 == 0){
System.out.println();
}
}
}
random.nextInt(n.length)
gives you a random index of your array.
But printing the value corresponding to this index, will always give you 0. As you never store any other value in the array.
You should rather do something like this :
int[] list = new int[10];
int duplicates = 0;
Random random = new Random();
for (int i = 0; i < list.length; i++) {
int nextVal = random.nextInt(list.length);
System.out.println("list["+i+"] = "+ nextVal);
// test duplicates
for (int index = 0; index < i; index++) {
if (list[index] == nextVal) {
duplicates++;
break;
}
}
list[i] = nextVal;
}
return duplicates;
Your generate_data method always returns 0, since the local field duplicates is initialized with a 0 value and never changed.
The n field referenced by your generate_data method (which you haven't posted) is likely to be an int[], but its elements might not have been initialized (hence the print out will print default value 0, if within array index).
Hence your numDuplicates local field is always 0 too.
Notes
Your Random initialization is not performing. You should initialize a static Random object in your class and re-use it, instead of re-initializing every time in your generate_data method.
You probably want to have a look at coding conventions for Java in terms of field naming
You might want to post the code in your printArray method as well
Sounds simple enough...but I've been plugging away at this, trying to find the one and all solution.
For a range of numbers, say 1-12, I want to generate a random sequence within that range, and include 1 and 12.
I don't want duplicate numbers though.
So I would want something like this - 3,1,8,6,5,4 ..and so on, every number from 1-12.
Then I want to put these random numbers into an Array and use that array to 'randomly' select and display some items (like inventory pulled from database) on a jsp page.
The problem with what I've tried thus far, is that there are a lot of duplicate numbers being generated...or, not ALL of the numbers are chosen.
Is there a simple solution to this problem?
Edit
Test#1 using Collections and shuffle() method -
ArrayList<Integer> list = new ArrayList<Integer>(10);
for(int i = 0; i < 10; i++)
{
list.add(i);
}
Collections.shuffle(list);
String[] randomNumbers = (String[])list.toArray();
for(int i = 0; i < 10; i++)
{
out.print(randomNumbers[i]+"<br>");
}
The result was a sequence with duplicate values -
chose = 3
chose = 8
chose = 7
chose = 5
chose = 1
chose = 4
chose = 6
chose = 4
chose = 7
chose = 12
Test #2 - using Random math class
int max = 12;
int min = 1;
int randomNumber = 0;
String str_randomNumber = "";
for(int i=0; i<10; i++) {
//int choice = 1 + Math.abs(rand.nextInt(11));
int choice = min + (int)(Math.random() * ((max - min) + 1));
out.print("chose = "+choice+"<br>");
}
The result was just like using Collections.shuffle().
You can fill an array with all values from 1 to 12 and then shuffle them (see e.g. Why does Collections.shuffle() fail for my array?)
You can put all numbers from 1 to 12 in order into array and then use some shuffling algorithm to randomize the order of them e.g. http://www.leepoint.net/notes-java/algorithms/random/random-shuffling.html.
Random number generation allows for duplications. If you want a range of random numbers without duplication, I suggest the following:
Generate a random number (I will refer to this a numberX).
Add to a Set object.
Check the size of the Set object, if it is the desired size, you are done. If it is smaller than the desired size, goto step 1
If you are using MySQL or SQLLite as your database you can do this randomization at the SELECT query level by using ORDER BY RAND() for restricting to 1-12 you can put a where clause WHERE ID >=1 AND ID <=12 ORDER BY RAND()
This is a utility method for creating a random Integer number :
public static int randomInteger(int min, int max) {
Random rd = new Random();
return rd.nextInt((max - min) + 1) + min;
}
This is an algorithm that always produces a unique Set of integers:
public static Set<Integer> makeRandomSet(int howManyNumber, int startNumber, int endNumber){
Set<Integer> integerSet = new HashSet<>();
boolean couldBeAdded = false;
for(int i=0; i< howManyNumber; i++) {
while (!couldBeAdded) {
Integer randomInt = randomInteger(startNumber, endNumber);
couldBeAdded = integerSet.add(randomInt);
}
couldBeAdded = false;
}
return integerSet;
}
We made use of add method return type to check the duplicate value within our Set.
And here is the test code:
public static void main(String[] args) {
Set<Integer> randomSet = makeRandomSet(6, 1, 54);
System.out.println(randomSet);
}
The output of the above code is 6 random unique integers number
between 1 and 54
You could just put all the numbers you want in a List and then order the List randomly and then convert the randomly ordered list to an array, e.g.
List<Integer> list = new ArrayList<Integer>();
for (int i = 1; i <= 12; i++) {
list.add(i);
}
Collections.sort(list, new Comparator<Integer>() {
#Override
public int compare(Integer o1, Integer o2) {
return Math.random() > 0.5 ? 1 : -1;
}
);
Integer[] array = list.toArray(new Integer[list.size()]);