exclude number from the Random picker list - java

i have a Random picker code that picks random number for ex from 1 to 6 ..
can u give me a method how to exclude the picked number from the list of random pick ..
import java.util.Random;
Random rand = new Random();
int n = rand.nextInt(6) + 1;
like that for ex :
1.2.3.4.5.6
random pick=5
1.2.3.4.6
random pick=2
1.3.4.6
.. etc
ty in advance guys

You can add the numbers that have already been picked to an ArrayList and pick a number until the number is not contained in the list.
// list of numbers that I already picked
ArrayList<Integer> randomNumbersPicked = new ArrayList<>();
// int to save the current random number
int myCurrentRandomNumber;
while(iNeedAnotherNumber){
do {
myCurrentRandomNumber = generateRandomNumber(a, b);
//repeat this until the number is not in the list
} while (randomNumbersPicked.contains(new Integer(myCurrentRandomNumber)));
//here there is a unique random number, do what you will
System.out.println("A new number has been picked: " + myCurrentRandomNumber);
//add the number to the list so it wont be picked again
randomNumbersPicked.add(new Integer(myCurrentRandomNumber));
}
Best Regards!
Dknacht.

Put all valid numbers into an ArrayList and instead select a random index from the list. Then remove that number from the list and repeat.
My Java is a little rusty, so hopefully the code I write makes sense:
ArrayList<int> validOptions = /**/; // make your list with all initial options
int firstIndex = random.Next(validOptions.count());
int firstPick = validOptions.get(firstIndex);
validOptions.removeAt(firstIndex);
int secondIndex = random.Next(validOptions.count());
int secondPick = validOptions.get(secondIndex);
validOptions.removeAt(firstIndex);

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 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.

Creating objects with random attributes

I'm building a railway simulator including the classes Passenger and Station (among others). The Passenger class has an attribute endLoc, which will be the desired end location for each passenger (i.e. a station object). I'm generating a random number of passengers at each station on my network into an ArrayList, and would like their attribute of endLoc to be randomly generated as well (out of a list of all the station objects), but I can't work out how to make the attribute be a random one from a list each time.
ArrayList<Passenger> passengers = new ArrayList<Passenger>();
for (int i = 0; i<p; i++){
passengers.add(new Passenger(statA));
i.e. Once I have my random number, and have it mapped to which station I want, what do I put in the code instead of statA, to mean the station that applies to my random number?
Can anyone tell me how to do this, or at least point me in the right direction? Thanks.
Write something like this:
List<String> stations = new ArrayList<String>();
//add stations..in the list
int numStations = stations.size();
int maxPassengersAtStation = 100;//assgin you number
for(int sCount=0; sCount<numStations; sCount++){
int passangersAtStation = (int)(Math.random() * maxPassengersAtStation);
for(int j=0; j<passangersAtStation; j++){
int passengerDestination = sCount + (int)(
Math.random() * ((numStations - sCount) + 1));
passengers.add(new Passenger(stations.get(passengerDestination)));
}
}
Well, some random ideea would be to generate a number from 1 to your_list.length and then take that object from the list and assing it to your endLoc.
Generate a random int x and then do x = x % allStations.size();
The x would be your random index of the list with all stations.

Generating an array of random points in java with no duplicates

I am fairly new to Java, and I want to generate an array of random (x,y) coordinates of length 'number' that contains no duplicates. x or y values can be repeated, but there must be no repeated (x,y) coordinates. The output does not have to be Points, simply some way of holding x,y values for coordinates.
I can generate an array of random points, and have tried using a Set to ensure there are no duplicate values, but have run into problems. I tried using the condition "while (set.size)" and the 'add' method which should disallow duplicates, to create an output of the correct size which contains unique points.
This is the code:
Set<Point> set = new HashSet<Point>();
Random position = new Random();
Point test=new Point();
do{
test.x=position.nextInt(xx);
test.y=position.nextInt(yy);
//xx and yy are the random number limits called from another part of the code
set.add(test);
}
while (set.size()<number);
List<Object> list = new ArrayList<Object>(set);
Object[] coord = list.toArray();
This outputs an array of the correct length, but every element is the same. Can anyone offer any help?
Thanks
test points to the same variable in space everytime you loop, to fix that create a new instance inside the loop - not just once before it:
Set<Point> set = new HashSet<Point>();
Random position = new Random();
Point test;
do{
test = new Point();
test.x=position.nextInt(xx);
test.y=position.nextInt(yy);
//xx and yy are the random number limits called from another part of the code
set.add(test);
}
while (set.size()<number);
List<Object> list = new ArrayList<Object>(set);
Object[] coord = list.toArray();
You are modifying the same point object. However, since you change X and Y every time, you also changing hash code and equality of the point, so you end up placing the same object multiple times in the set. Interesting case.
try
do{
test = new Point();
test.x=position.nextInt(xx);
test.y=position.nextInt(yy);
//xx and yy are the random number limits called from another part of the code
set.add(test);
}
while (set.size()<number);
Value select Randomly but not repeated
Random rndm = new Random();
String[] selectedNumber = new String[15];
String[] sequanceNumber = {"1","2","3","4","5","6","7","8","9","10","11","12","13","14","15"};
//*****FIRST LOOP START*****//
for(byte a = 0; a < 15;){
int temp = rndm.nextInt(15)+1;
//*****SECOND LOOP START*****//
for(byte b = 0; b < 15; b++){
String s4 = temp+"";
//*****CHECKING CONDITION START*****//
if(s4.equals(sequanceNumber[b]) ){
selectedNumber[a] = s4;
String s1 = sequanceNumber[b];
s1 = s1.replace(s1, " ");
sequanceNumber[b] = s1;
a++;
}
//*****CHECKING CONDITION END*****//
}
//*****SECOND LOOP END*****//
}
//*****FIRST LOOP END*****//
//*****PRINT ALL RANDOM VALUES BUT NOT REPEATED VALUES*****//
System.out.println(Arrays.toString(selectedNumber));

Android Random Number

I m generating one random card from array. and assigning it.'
Below is the code..but its is showing an error.
What is the problem?
public void rand() {
String rank[]= {"tclub1.png", "tclub2.png", "tclub3.png", "tclub4.png", "tclub5.png", "tclub6.png", "tclub7.png", "tclub8.png", "tclub9.png", "tclub10.png","tclub11.png", "tclub12.png", "tclub13.png"};
Random randInt = new Random();
int b = randInt.nextInt((rank.length));
showcard1.setBackgroundResource(b);
}
b is an int
so you need rank[b] the array at some point in your code
According to your code maybe it should read
showcard1.setBackgroundResource(rank[b]);
Try changing to int b = randInt.nextInt((rank.length)) - 1; (because rank.length = 13 and your array is indexed from 0 to 12)

Categories