How to set a different random number to all buttons? - java

I have 4 buttons in an array. I am able to generate a random number and set it to all those buttons, but that's not what I intend to do. What I really want to do it set a random number to each button. E.g: instead of having '17' inside all four buttons, I may have '18', '15', '10', and '11' in each button. Instead of manually assigning a random in to each button, how could I do this to all buttons?
Here's my code:
Random rbselection = new Random();
final int rbselector = rbselection.nextInt(4);
final Button[] selectrb = new Button[4];
selectrb[0] = rb1;
selectrb[1] = rb2;
selectrb[2] = rb3;
selectrb[3] = rb4;
Random randoms1 = new Random();
int setRandoms1 = randoms1.nextInt(10);
for(int allrbA=0; allrbA<4; allrbA++) {
selectrb[allrbA].setText(""+setRandoms1);
}
Also, does anyone know how to stop a single number from being outputted twice when doing this? For example if the random numbers set are between 10 and 20 and one of them is 12, anyone know how to make all other possible numbers anything between that range apart from 12?

If I were you..
public static void main(String[] args) {
Set<Integer> uniqueRandomNumbers = new LinkedHashSet<>();
while (uniqueRandomNumbers.size() != 4) {
Random random = new Random();
uniqueRandomNumbers
.add(Math.abs(Integer.valueOf(random.nextInt())));
}
System.out.println(uniqueRandomNumbers);
}
Explanation :
I am generating random numbers. First I got random number 100, I added it to a 'Set' as set always maintains the uniqueness, if I get 100 again by any chance the size of the Set won't be increasing.
When size of the Set is 4 the loop breaks and the set contains unique random numbers.
Iterate through the Set to set the text.

To get random number in Java:
Random rand = new Random();
int n = rand.nextInt(50) + 1;
Where 1 is going to be your minimum in the range and 50 is going to be your max. Use this link for reference: Getting random numbers in Java
Depending on how many buttons you have. You could have
rbselection.nextInt(50) + 1;
to generate a new Int between 1 to 50 range every time u call it and add it to some list or Set.
So something like this:
Random rand = new Random();
int n = rand.nextInt(50) + 1;
ArrayList<Integer> ar = new ArrayList<Integer>();
int i = 0;
while (i < 4)
{
int temp = rbselection.nextInt(50) + 1;
if (ar.contains(temp))
continue;
ar.Add(temp);
i++;
}
Also, u can change the above code to something like:
while (i < 4)
{
int temp = rbselection.nextInt(50) + 1;
if (ar.contains(temp))
continue;
array[i].setText(temp);
ar.Add(temp);
i++;
}
Where array is the button array of size 4.

Try this:
Random rnd = new Random();
for(int allrbA=0; allrbA<4; allrbA++)
selectrb[allrbA].setText(String.valueOf(rnd.nextInt(20)));

Related

How can I add 100 random elements to an empty array with duplicates?

In this code, I'm shuffling 100 random elements instead of adding 100 random elements with duplicates, and returning 10 unique keys. How can I do that?
public static void main(String[] args) {
ArrayList<Integer> uniqueKeys = new ArrayList<Integer>();
for (int i = 0; i < 101; i++) {
uniqueKeys.add(new Integer(i));
}
Collections.shuffle(uniqueKeys);
for (int i = 0; i < 10; i++) {
System.out.println(uniqueKeys.get(i));
}
}
I suggest using a combination of Set and Random. Using Set, you will get rid of duplicates. Using Random, you will get (pseudo) random numbers.
final int KEYS_COUNT = 100;
final int MAX_KEY_VALUE = 1000;
Set<Integer> setOfKeys = new HashSet<>();
Random random = new Random();
while (setOfKeys.size() <= KEYS_COUNT) {
setOfKeys.add(random.nextInt(MAX_KEY_VALUE));
}
The Set setOfKeys will contain 100 unique random numbers with their values less then 1000. You can then use toArray() method to make array from the Set.
If you make KEYS_COUNT equal to MAX_KEY_VALUE, the values won't be much random, they will be only shuffled.

Get random strings from a list

I have an ArrayList which is defined outside the main method, just inside the class StringRandomize:
public static ArrayList<String> countries = new ArrayList<String>();
I also initialized a random object.
Random obj = new Random();
Then I add some Strings to the list:
StringRandomize.countries.add("USA");
StringRandomize.countries.add("GB");
StringRandomize.countries.add("Germany");
StringRandomize.countries.add("Austria");
StringRandomize.countries.add("Romania");
StringRandomize.countries.add("Moldova");
StringRandomize.countries.add("Ukraine");
How do I make those strings appear randomly? I need output like "Germany", "Moldova" and so on.
I need exactly the strings in the output, not their IDs.
Thanks for your help.
You probably want to use something like:
countries.get(Math.abs(new Random().nextInt()) % countries.size());
Or, to avoid creating a new Random object every time, you could use the same one:
Random gen = new Random();
for (int i = 1; i < 10; i++) {
System.out.println(countries.get(Math.abs(gen.nextInt()) % countries.size()));
}
I would use Collections.shuffle(countries) if you wanted a randomized List.
Else a new Random().nextInt(max) like Flavius described.
static void shuffleArray(string[] ar)
{
//set the seed for the random variable
Random rnd = ThreadLocalRandom.current();
//go from the last element to the first one.
for (int i = ar.size()- 1; i > 0; i--)
{
//get a random number till the current position and simply swap elements
int index = rnd.nextInt(i + 1);
// Simple swap
int a = ar[index];
ar[index] = ar[i];
ar[i] = a;
}
}
This way you shuffle the entire array and get the values in a random order but NO duplicate at all. Every single element changes position, so that no matter what element (position) you pick, you get a country from a random position. You can return the entire vector, the positions are random.

Assigning random value to JButton

I need to assign different number from 1 to 8 to JButton Array. But the elements of array has to be different.
Random random = new Random();
JButton[] number = {jButton1,jButton2,jButton3,jButton4,jButton5,jButton6,jButton7,jButton8,jButton9};
for(int i = 0; i<data.lentgh; i++)
{
number[i].setText(1+random.nextInt(9)+" ");
}
With this code, the elements of array can be different and sometimes some of elements can be same. I searched the internet but I couldn't find.
How can I fix this? Thank you.
You can do it without random()
for(int i = 0; i<data.lentgh; i++) // I think data should be replaced by number
{
number[i].setText((i+1)+"");
}
It is not necessary that random() will always generate different no. Most of the time you will get no. which is already generated.
Maybe you can use LinkedHashSet to store the random number and then later you can iterate over the set and set the text of the button.
Random random = new Random();
JButton[] number = { jButton1, jButton2, jButton3, jButton4, jButton5,
jButton6, jButton7, jButton8, jButton9 };
Set<Integer> set = new LinkedHashSet<Integer>();
while (set.size() != 9) {
set.add(1+random.nextInt(9));
}
int i = 0;
for (Integer s : set) {
number[i].setText(s + " ");
panel.add(number[i]);
i++;
}

random numbers previously established (java)

The following code shows 4 int variables:
int xy1 = 724329;
int xy2 = 714385;
int xy3 = 715440;
int xy4 = 696492;
I'm pretending to code an app that, by opening it, shows one of those numbers (NOT numbers between them) on java console, randomly. I know that Math.Random class can be used to solve these kind of issues, but I don't know what is the proper way to do so.
So, thanks.
Well it sounds like you just want a collection of possible values, and an index between 0 and 3 inclusive:
int[] values = { 724329, 714385, 715440, 696492 };
Random random = new Random(); // Ideally initialize once for the entire app
int index = random.nextInt(4);
int value = values[index];
Place them into an array and use Random to select a number between 0-3 and use it as a key to select the value from the array.
Try this one.
This line
r.nextInt(nums.length)
selects an integer from 0 to nums.length-1.
Then I print out the randomly selected number from the nums array.
I repeat this 20 times just for demonstration purposes.
import java.util.Random;
public class Test015 {
public static void main(String[] args) {
int[] nums = {724329, 714385, 715440, 696492};
Random r = new Random();
for (int i=0; i<20; i++){
int index = r.nextInt(nums.length);
System.out.println("Number randomly chosen: " + nums[index]);
}
}
}

Two random number generators (card dealing)

I need help with this part of my code. This part deals with generating 2 random numbers and using that random number to display a card in each of 2 label boxes simultaneously. The problem here is the random numbers are not getting generated properly and thus cards are not displayed properly (there is repetition, sometimes no display, etc)
Basics of my code:
Let us assume h, which is a variable from another part of the code, is any number between 1 and 53 (each number pertaining to a card). If the random number generated (non-repetition) matches the variable h the timer stops.
So its basically like having a deck of cards and dealing out the cards evenly to 2 people, but here the dealing stops once a number pertaining to a card (number) randomly taken is matched.
(l3,l4 are label names)
Global variables:
Random rng = new Random();
List<Integer> generated = new ArrayList<Integer>();
List<Integer> generated2 = new ArrayList<Integer>();
int l3count;
int l4count;
int Ulim = 53;
int Llim = 1;
int next;
int check;
int h;
int next2;
int Ulim2 = 53;
int Llim2 = 1;
final int p = h;
int delay2 = 1000;
final Timer timer2 = new Timer();
timer2.schedule(new TimerTask(){
public void run(){
for (int i = 1; i < 53; i++)
{
while(true)
{
next = rng.nextInt(Ulim) + Llim;
if (!(generated.contains(next)||generated.contains(next2)))
{
generated.add(next);
break;
}
next2 = rng.nextInt(Ulim2) + Llim2;
if (!(generated.contains(next)||generated.contains(next2)))
{
generated.add(next2);
break;
}
}
String a = Integer.toString(next);
String c = "C:\\Users\\mycompname\\Desktop\\deck\\"+a+".png";
String d = Integer.toString(next2);
String e = "C:\\Users\\mycompname\\Desktop\\deck\\"+d+".png";
for(int j = 1;j<=53;j++)
{
if(j%2==0)
{l3.setIcon(new ImageIcon(c));
}
else
{l4.setIcon(new ImageIcon(e));
}
}
if(next==p||next2==p)
check=10;
break;
}
if(check==10)
timer2.cancel();
timer2.purge();
}
},delay2, 1000);
Any help would be appreciated.
Thanks for your time.
You'd be better off dealing the cards out randomly.
Using the O(n) Knuth Shuffle you can pass along one card at a time, from one array to another.
Each new array you pass the card to will be a different persons' hand.
Keep adding 1 card at a time to each array from the deck array until each player has the number of cards your rules require.
Also, don't rely on random numbers being equal. See stupid-sort. Look for some other pattern instead. Like a random number of cards % cards_left you should stop giving out cards.
Update with code-sample, as per request:
public static void shuffle (int[] array) {
for(int n = array.length; (n > 1);) {
int k = gen.nextInt(n--);
int temp = array[n];
array[n] = array[k];
array[k] = temp;
}
}
The obvious problem is that Random.nextInt generates a number 0 (inclusive) and n (exclusive). So when you pass in a limit of 53, you're generating values between 0 and 52 — that's 53 possible values, and there aren't that many cards. So change the upper limit to 52.
Also, as other answers note, the reason you're getting collisions (dealing the same card to multiple hands), etc. is that you don't want to randomly select the cards. You actually want to randomly shuffle the deck.
Try using a shuffle algorithm instead.

Categories