Error when generating large numbers with a condition - java

I need to generate players(any number) of large numbers with the condition that all of them will be less than P. But for some reason, when generating the resulting array, it either goes beyond the players range or generates numbers greater than P. How to generate it correctly?
ArrayList<BigInteger> C = new ArrayList<>(players);
for(int i = 0; i < players; i++) {
do {
C.add(i, new BigInteger(64, random));
} while (C.get(i).compareTo(P) > 0);
}

the reason for your error is you are adding the integer into the C regardless whether the generated number is larger than P. meaning your list will grow larger than your players
also please follow the naming convention and use camel case for your variable names
do sth like this instead
ArrayList<BigInteger> integerList = new ArrayList<>(players);
while (integerList.size()<players-1){
BigInteger randomInt = new BigInteger(64, random);
if(randomInt.compareTo(p) > 0){
integerList.add(randomInt);
}
}

Related

How to generate random unique numbers on java

I'm new to Java and im trying to randomize non-repeating numbers for a game. My code generates unique random numbers from 1 to 75 only if i do not add a break statement, (which i have to do to only get one number at the time). What do I do? edit -(i was wondering if the reason it kept resetting is because i called on the method multiple times? im not too sure how to fix that)
public static void genNumber() {
Random random = new Random();
int num;
String u;
String letter = "";
HashSet<Integer> used = new HashSet<>(75);
for (int i = 1; i <= 75; i++){
ball.add(i);
}
while(used.size() > 0) {
num = 1 + random.nextInt(75);
if (used.contains(num)){
used.remove(new Integer(num));
u = Integer.toString(num);
System.out.print(u + "\n");
break;
}
if (!used.contains(num)){
continue;
}
}
The numbers are unique and random but i only want one number at the time (without repeating) not all 75 at once.
Perhaps shuffle the list each time you want a new random sequence, like a deck of cards. Each element is guaranteed to be unique.
List<Integer> balls = new ArrayList<>();
for (int i = 1; i <= 75; ++i) {
balls.add(i);
}
for (;;) {
// Shuffle the list every 75 draws:
Collections.shuffle(balls);
System.out.println(Arrays.toString(balls.toArray()));
// Consume the sequence
for (Integer ball : balls) {
take(ball);
}
}
I would make a 75 element array of boolean values and set all the values to true. Make a method that generates one random number and update your boolean array at that value to false. Each time you generate a number check your array to see if that value is set to true. Then you can keep generating numbers one at a time and not have to worry about getting repeats. You can have a while loop that asks the user to input yes or no and if they answer no it won't call your method and set your while loop condition to false. and if they answer yes it does call the method and keeps looping.

How to stop Random from generating everytime besides the first time?

Hello everyone I have this command:
for (z = 0; z < utenti.length; z++) {
utenti[z] = rand.nextInt(1000) + 1;
}
After it's done generating random numbers between 1 and 1000 I want it to stop, the command is one of the functions in my program, but everytime i recall it the numbers generete randomly again. Is there a way to stop the random generation after the first time?
Is there a way to stop the random generation after the first time?
Yes. Don't execute that code after the first time. For example:
if (firstTime) {
for (z = 0; z < utenti.length; z++) {
utenti[z] = rand.nextInt(1000) + 1;
}
firstTime = false;
}
I you don't want to run the piece of code twice, then why are you calling it twice?
Since this piece of code is required to be executed just once, it probably is in the wrong place. It perhaps belongs in a constructor or something, depending on your program structure.
You might just do what Stephen C did in his answer, using a boolean to keep track of whether it's the first time or not. That might be the simplest option for you.
In addition to the other answer, also note that one the constructors of the Random class accepts a seed. If you keep the seed the same, the sequence of pseudo-random numbers will be the same. This saves you the memory usage of the utenti array, especially with large arrays.
private long seed;
private void determineSeed() {
long seed = new Random().nextLong();
}
And then use:
Random rand = new Random(this.seed);
for (int i = 0; i < utenti.length; i++) {
int number = rand.nextInt(1000) + 1);
// Don't save it to an array, do something with number
}
A drawback is that you cannot usage specific element of the sequence (for example, utenti[i]), you must use the random numbers in sequence.

Java - Improper Checking in For Loop

This is a chunk of code in Java, I'm trying to output random numbers from the tasks array, and to make sure none of the outputs are repeated, I put them through some other loops (say you have the sixth, randomly-chosen task "task[5]"; it goes through the for loop that will check it against every "tCheck" element, and while task[5] equals one of the tCheck elements, it will keep trying to find another option before going back to the start of the checking forloop... The tCheck[i] elements are changed at the end of each overall loop of output to the new random number settled on for the task element).
THE PROBLEM is that, despite supposedly checking each new random task against all tCheck elements, sometimes (not always) there are repeated tasks output (meaning, instead of putting out say 2,3,6,1,8,7,5,4, it will output something like 2,3,2,1,8,7,5,4, where "2" is repeated... NOT always in the same place, meaning it can sometimes end up like this, too, where "4" is repeated: 3,1,4,5,4,6,7,8)
int num = console.nextInt();
String[] tasks = {"1","2","3","4","5","6","7","8"};
String[] tCheck = {"","","","","","","",""};
for(int i = 0; i<= (num-1); i++){
int tNum = rand.nextInt(8);
for(int j = 0; j <=7; j++){
if(tasks[tNum].equals(tCheck[j])){
while(tasks[tNum].equals(tCheck[j])){
tNum = rand.nextInt(8);
}
j = 0;
}
}
tCheck[i] = tasks[tNum];
System.out.println(tasks[tNum]+" & "+tCheck[i]);
}
None of the other chunks of code affect this part (other than setting up Random int's, Scanners, so on; those are all done correctly). I just want it to print out each number randomly and only once. to never have any repeats. How do I make it do that?
Thanks in advance.
Firstly, don't use arrays. Use collections - they are way more programmer friendly.
Secondly, use the JDK's API to implement this idea:
randomise the order of your elements
then iterate over them linearly
In code:
List<String> tasks = Arrays.asList("1","2","3","4","5","6","7","8");
Collections.shuffle(tasks);
tasks.forEach(System.out::println);
Job done.
you can check if a certain value is inside your array with this approach.
for(int i = 0; i<= (num-1); i++){
int tNum = rand.nextInt(8);
boolean exist = Arrays.asList(tasks).contains(tNum);
while(!exist){
//your code
int tNum = rand.nextInt(8);
exist = Arrays.asList(tasks).contains(tNum);
}
}
if you are using an arraylist then you can check it with contains method since you are using an array we have to get the list from the array using asList() and then use the contains method. with the help of the while loop it will keep generating random numbers untill it generates a non duplicate value.
I used to created something similar using an ArrayList
public class Main {
public static void main(String[] args) {
String[] array = { "a", "b", "c", "d", "e" };
List<String> l = new ArrayList<String>(Arrays.asList(array));
Random r = new Random();
while(!l.isEmpty()){
String s = l.remove(r.nextInt(l.size()));
System.out.println(s);
}
}
}
I remove a random position in the list until it's empty. I don't use any check of content. I believe that is kind of effective (Even if I create a list)

Unable to use Set to remove duplicate pair numbers

Let's say I want to generate 20 random numbers on a 8 by 6 grid.(8 columns, 6 rows) . Based on the answer from here:Creating random numbers with no duplicates, I wrote my code like this:
Random randomNumGenerator = new Random();
Set<Integer[][]> generated = new LinkedHashSet<Integer[][]>();
while (generated.size() < 20) {
int randomRows = randomNumGenerator.nextInt(6);
int randomColumns = randomNumGenerator.nextInt(8);
generated.add(new Integer[][]{{randomRows,randomColumns}});
}
In reality what happens is the Set see Integer[][]{{5,5}}; and Integer[][]{{5,5}};as NOT duplicate.Why? Even tho my purpose is to get 20 non-duplicate pair of numbers, this does not work. How do I fix this?
The Set checks for duplicates using the equals method (and also the hashCode method) of its inner type, but the Integer[][]'s equals method compares the memory addresses and not the contents.
Why do you use a Set of Integer[][] if you just want to store pairs?
Unfortunately, in Java there is no Pair class, but if you do not want to create your own, you can use the Map.Entry for that.
Random randomNumGenerator = new Random();
Set<Map.Entry<Integer, Integer>> generated = new LinkedHashSet<>();
while (generated.size() < 20) {
int randomRows = randomNumGenerator.nextInt(6);
int randomColumns = randomNumGenerator.nextInt(8);
generated.add(new AbstractMap.SimpleEntry<>(randomRows,randomColumns));
}
System.out.println(generated);
Array equals is == in Java, so an array is only equal to itself. Normaly you use Arrays.equals(array1, array2) to compare them by content, but in this case, arrays are simply the wrong choice. You can either create a bean, as rafalopez79 suggested of use an array of Collections (List in your case), as a List will compare the content on equals, see the documentation. Choice is pretty much yours, a bean would probably be a bit cleaner.
How about this code. I ran it through the debugger, it works nicely and yes, the contains() method checks the value of the Integer, not the reference. You can change the range of the random number as needed, I used 5 to facilitate testing. Yes I know it's not very robust, as written this will be an endless loop (because of the limited range of 5) but it's a simple example to make the point.
UPDATE: Actually this has a bug in that it won't check for uniqueness across all the rows, but that's easily fixed as well. I just re-read the original question and looking at the original code I'm not sure I know what you want exactly. If you just want a grid with 48 unique Intergers arranged 8 by 6 this will do it, but there are several ways to do this.
final int rows = 6;
final int cols = 8;
Random randomGenerator = new Random();
ArrayList[] grid = new ArrayList[rows];
for(int i=0; i<rows; i++)
{
grid[i] = new ArrayList<Integer>();
for(int j=0; j<cols; j++)
{
for(;;)
{
Integer newInt = new Integer(randomGenerator.nextInt(5));
if(!grid[i].contains(newInt))
{
grid[i].add(newInt);
break;
}
}
}
}

How to get unique random int?

static int n = -1;
private static int repeatBuffer[] = new int[10];
static {
repeatBuffer[0] = 0;
//and more
repeatBuffer[9] = 9;
}
static public void randomize() {
do {
Random r = new Random();
randomNumber = r.nextInt(20);
} while (!uniqueInt(randomNumber));
Log.e(TAG, "" + randomNumber); //here I need have a unique int
}
private static Boolean uniqueInt(int random) {
for (int i = 0; i < 9; i++) {
if (random == repeatBuffer[i]) {
return false;
}
}
if (++n > 9)
n = 0;
repeatBuffer[n] = random;
return true;
}
Sometimes I'm getting same int twice, I'm wondering where is the problem? And is it even work? I spend quite a lot of time on this, and I give up. I think I need some minor tweaks in code :)
An easier way to get a random int is to create a List of integers List<Integer>, adding it with numbers that you would like to have. Then shuffling the List using Collections.shuffle(list);. Now start reading from the beginning of the list and you will get a unique random int each time.
Just make sure that each time you "read" a number from the list, either remove it from the list or increase the index for where you read.
That's the normal behavior of a random number generator, it's correct to generate repeated numbers as long as the number distribution remains uniform.
If you need a set of unique random numbers, you can generate them inside a loop and ask at every iteration if the newly generated number is present in the set of generated numbers. If not, add it, if yes, keep iterating - until the set has the desired size.
Er, a unique random between 1 and 20? What happens when it runs the 21st time?
Try making a List of the Integers between 1 and 20. Use Collections.shuffle() to shuffle the list. Then pop the first item off the front of the list and use that.

Categories