Randomly take an int element from an integer array - java

I have an Integer array and I want to randomly take an element from those who are not null. I have tried this but after the else, I cannot use return because the method is int. But I don't know what to write after else in order to return at the beginning and take a new random element.
public int getRandomPosition(){
Random x = new Random();
int b = x.nextInt(2*number0fCardPairs);
if (myArray[b] != null){
return b;
}
else{
return;
}
}

You could make your method recursive:
private Random x = new Random();
public int getRandomPosition(){
int b = x.nextInt(sizeOfArray);
if (myArray[b] != null){
return b;
}
// else {
return getRandomPosition();
}
or using a while-loop
private Random x = new Random();
public int getRandomPosition(){
Integer result = null;
do {
int index = x.nextInt(sizeOfArray);
result = myArray[index];
} while (result == null);
return result.intValue();
}
Theoretically, however, the method could run indefinitely if you're really unlucky. Therefore, it probably makes sense to include a counter, so for example only try max. 20 times, then return null:
private Random x = new Random();
public int getRandomPosition(){
Integer result = null;
int tries = 0;
do {
int index = x.nextInt(sizeOfArray);
result = myArray[index];
} while (result == null && ++tries < 20);
return result.intValue();
}

You can achieve this by using a loop.
public int getRandomPosition(){
Random random = new Random();
int randomIdx = random.nextInt(array.length);
// while array at randomIdx is null, continue getting new randomIdx
while (array[randomIdx] == null) {
randomIdx = random.nextInt(array.length);
}
return randomIdx;
}
Note that if all the elements inside the array are null, it will be an infinite loop. Hope you find this helpful!

You can do:
Integer[] myArray = {1,2,3,null,5};
List<Integer> nonNullIntegers = Arrays.stream(myArray)
.filter(Objects::nonNull)
.collect(Collectors.toList());
Random random = new Random();
Integer randomInteger = nonNullIntegers.get(random.nextInt(nonNullIntegers.size()));

Related

Random number generator generates duplicates

Framework: Java
public static List<Integer> buttonIdList = new ArrayList();
public void myMainMethod() {
for(Integer i = 0; i < 11; i++) {
int randomButtonId = getUniqueIdNumber();
}
}
private static Integer getUniqueIdNumber() {
Random ran = new Random();
int randomButtonId = ran.nextInt(20) + 1;
if(buttonIdList.contains(randomButtonId)) {
getUniqueIdNumber();
} else {
buttonIdList.add(randomButtonId);
}
return randomButtonId;
}
When the code encounters a duplicate, it calls itself (recursively) and in the second try if the number is unique the return statement returns it to the myMainMethod or to getUniqueIdNUmber?
Where should the return statement be placed?
You should return the result of the recursive call:
private static Integer getUniqueIdNumber() {
Random ran = new Random();
int randomButtonId = ran.nextInt(20) + 1;
if(buttonIdList.contains(randomButtonId)) {
return getUniqueIdNumber();
} else {
buttonIdList.add(randomButtonId);
}
return randomButtonId;
}
P.S., it would be better to make Random ran a static variable instead of creating a new Random instance in each recursive call.
private static Random ran = new Random();
private static Integer getUniqueIdNumber() {
int randomButtonId = ran.nextInt(20) + 1;
if(buttonIdList.contains(randomButtonId)) {
return getUniqueIdNumber();
} else {
buttonIdList.add(randomButtonId);
return randomButtonId;
}
}
And you might consider changing buttonIdList to a HashSet (or LinkedHashSet if you care about insertion order) in order to make the search for existing number more efficient.

Exchange variable in non specified method

Im a newcomer :)
However, my program has a table and a RandomGen should get the highest random int by getRowCount -> checkvar1.
Now, the main class gets checkvar1 and sends it to setVariable(), then I want to exchange this checkvar1 with randomGen to limit the maximum generated integer.
So this of course doesn't work because the parameters in randomGen() aren't set and I cannot set them, because then the exchange to the onActionPerformed() method in my main class doesn't work anymore.
public final class RandomGen
{
// EXCHANGE OF CHECKVAR1 FOR RANDOM GEN
public static void setVariable(int checkvar1)
{
System.out.print(checkvar1);
}
// RANDOM GENERATOR
public static int randomGen()
{
Random rand = new Random();
int var1 = rand.nextInt(checkvar1) + 1;
return var1;
}
}
Here my main class:
public void onActionPerformed(java.awt.event.ActionEvent evt) {
//NUMBER OF LAST ROW
int checkvar1 = (Integer)jTable1.getRowCount();
//->EXCHANGE WITH setVariable()
RandomGen.setVariable(checkvar1);
if (checkvar1 >= 3) {
int recogvar1 = checkvar1 - 1;
Object checkobj1 = jTable1.getModel().getValueAt(recogvar1, 0);
if (checkobj1 == null){
//...
}
else {
int var1 = RandomGen.variable();
String result = var1 + "";
jTextField1.setText(result);
//System.out.print(result);
}
}
else {
String rule2 = "At least " + 3 + " rows should be filled";
jTextField1.setText(rule2);
}
You are doing nothing with your setVariable in your class RandomGen. So You only need to change this.
// RANDOM GENERATOR
public static int randomGen(int checkvar1)
{
Random rand = new Random();
int var1 = rand.nextInt(checkvar1) + 1;
return var1;
}
And in your main Method try this.
//NUMBER OF LAST ROW
int checkvar1 = (Integer)jTable1.getRowCount();
//->EXCHANGE WITH randomGenerator
checkvar1 = RandomGen.randomGen(checkvar1);

Method with int and int[] parameters

I have a method with two parameters but they are different types (int , int[]). The problem is in the caller, Eclipse will not compile because it says both of the parameters need to be integer types. The caller looks like this:
boolean uniqueTorF = isUnique(count, userArray[i]);
The method is this:
public static boolean isUnique(int oneCount, int[] multiCount) {
for (int i = 0; i < multiCount.length; i++) {
if (oneCount == multiCount[i]) {
return false;
}
}
return true;
}
This is my entire code:
public static void main(String[] args) {
int[] userArray;
userArray = new int[5];
int validCount = 0, i = 0, uniqueSoFar = 0;
System.out.println("Please print out 5 numbers between 50 and 100. ");
Scanner entry = new Scanner(System.in);
while (validCount < 5) {
int count = entry.nextInt();
boolean validTorF = isValid(count);
boolean uniqueTorF = isUnique(count, userArray[i]);
if (validTorF == true) {
userArray[i] = count;
validCount++;
i++;
if (uniqueTorF == true){
uniqueSoFar++;
}
} else {
System.out.println("That is not a valid number.");
}
}
}
public static boolean isValid(int validParameter) {
if (validParameter > 50 && validParameter < 100) {
return true;
} else {
return false;
}
}
public static boolean isUnique(int oneCount, int[] multiCount) {
for (int i = 0; i < multiCount.length; i++) {
if (oneCount == multiCount[i]) {
return false;
}
}
return true;
}
}
Get rid of the index [i]. userArray[i] is a single element of the array. userArray is the entire array.
boolean uniqueTorF = isUnique(count, userArray);
I'll bet it's saying the params ARE both integer types, not that they SHOULD BE. You're passing count and userArray[i], but you probably should be passing count and userArray.
Defined method expects second argument as array whereas the caller is sending specific element. So send the entire array as argument
The reason of the error is because you are passing the parameters wrongly...
When you do this:
boolean foo = isUnique(count, userArray[i]);
Then you are invoking the method with 2 int parameters, but you need a int, int [] instead...
You are for sure looking for something more like this:
boolean foo = isUnique(count, userArray);

pseudo-random for index on an infinite strip

I want to create a class that represents an infinite (2^32 can be considered as infinite) strip on which there are pseudo-random numbers. The interface should be very simple; the constructor should get an instance of Random; and there should be a method to get the random number for an index.
Note that I don't want to store a huge lookup table and precalculate it; I want it to be done on the fly.
public class InfiniteRandomStrip {
public InfiniteRandomStrip(Random r) {
...
}
public int getNumber(int index) {
// magic code here
}
}
Note that the code should pass the following test:
Random seed = new Random(123);
Random seed2 = new Random(123);
InfiniteRandomStrip strip = new InfiniteRandomStrip(seed);
InfiniteRandomStrip strip2 = new InfiniteRandomStrip(seed2);
int first = strip.getNumber(454); // consume the random
if(strip.getNumber(5) == strip2.getNumber(5) )
System.out.println("TEST1 OK");
if(first == strip.getNumber(454) )
System.out.println("TEST2 OK");
I've had no luck finding any example or algorithm for such a random list case. If such a problem has no solution, I will be glad to hear an explanation why.
You could clone the Random object in the getNumber method so that you start at the same seed each time. Then compute nextInt repeatedly until you get to the correct index.
int getNumber(int index) {
Random r = this.seed.clone();
for (int i = 0; i < index - 1; ++i) {
r.nextInt();
}
return r.nextInt();
}
public class InfiniteRandomStrip {
private final long seed;
public InfiniteRandomStrip(Random r) {
this.seed = r.nextLong();
}
public int getNumber(int index) {
return new Random(seed ^ index).nextInt();
}
}

Data from my class is null?

I have a class holding a boolean, and two doubles, and then an array of that class, I need the boolean and doubles to have defaults values of false, 0.0, and 0.0, and then I have function that refers to an element of the array and the moment I try to access an one of the variables from the class it throws an exception saying its null. Here is my class and my function calling it.
public class PanelData {
boolean flag = false;
double tempStart = 0.0;
double tempEnd = 0.0;
}
private PanelData[] panelInfo = new PanelData[115];
private void panelInfoHandler (int i, double timeStart, double timeEnd) throws SQLException
{
if (!panelInfo[i].flag) {
delete();
insert();
panelInfo[i].flag = true;
panelInfo[i].tempStart = timeStart;
panelInfo[i].tempEnd = timeEnd;
}
else if (panelInfo[i].tempStart <= timeStart && panelInfo[i].tempEnd >= timeEnd) {
}
else
{
insert();
panelInfo[i].tempStart = timeStart;
panelInfo[i].tempEnd = timeEnd;
}
}
here is how I call the class.
panelInfoHandler(9, parsedStart, parsedEnd);
new PanelData[115] creates an array of 115 null references. Have you populated panelInfo with references to actual objects?
At a minimum, you then need to loop through that array and create new instances of PanelData for each element in the array, e.g.
for (int i = 0; i < panelInfo.length; i++)
panelInfo[i] = new PanelData();
Your array is full of null elements until you initialize it. To clarify, if you create an array of primitive objects, you get an array of default (i.e. 0) values. However, an array of Objects gets created with null elements.
int[] myIntArray = new int[10]; // 10 default values of 0
Integer[] myIntegerArray = new Integer[10]; // 10 null elements
add this line and then assign the values:
if(panelInfo[i] == null) panelInfo[i] = new PanelInfo();
You need to do something like
for(int i=0;i<115; i++)
{
PanelInfo[i] = new PanelData();
}
(Or whatever is the correct Java Syntax)
public class PanelData {
boolean flag = false;
double tempStart;
double tempEnd;
public PanelData() {
flag = false;
tempStart = 0.0;
tempEnd = 0.0;
}
private PanelData[] panelInfo = new PanelData[115];
for(int i = 0; i < 115; i++)
panelInfo[i] = new PanelData();
Creating the default constructor lets you instantiate the variables with the default values (false, 0.0, 0.0) in this case so you can test if you are getting a vanilla object back or not.

Categories