random numbers previously established (java) - 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]);
}
}
}

Related

How to set a different random number to all buttons?

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)));

Random element generation without duplicates Java [duplicate]

This question already has answers here:
Creating random numbers with no duplicates
(20 answers)
best way to pick a random subset from a collection?
(10 answers)
Closed 7 years ago.
I am trying to get this code to run without duplicates but am having no success researching this area.
Its the start of a question I am doing which will ask the user to input the missing element. However, when I generate random elements I am getting duplicates
import java.util.Random;
public class QuestionOneA2 {
public static void main(String[] args) {
String[] fruit = {"orange", "apple", "pear", "bannana", "strawberry", "mango"};
Random numberGenerator = new Random();
for (int i = 0; i < 5; i++) {
int nextRandom = numberGenerator.nextInt(6);
System.out.println(fruit[nextRandom]);
}
}
}
There are many different approaches you can consider, depending on how flexible the algorithm should be.
Taking 5 random elements from a list of 6, is the same as selection 1 element from the list of 6 that you don't choose. This is a very inflexible, but very easy.
Another approach could be to delete the element from the list, and decrease the maximum random number. In this cause I would advice to not use a String[].
When you generate a random number, I suggest adding it into an array.
Then, when you generate your next number, do some sort of search (google for something efficient) to check if that number is already in the array and thus, has been used already.
If it is, generate a new one, if its not, use it.
You can do this by nesting it in a while loop.
Although, from what I can tell from your question, you would be better off just creating a copy of your fruit array using an ArrayList and then, when you generate a random number to select a fruit, simply remove this fruit from this new list and decrement the range of random numbers you are generating.
You can use a Set to validate if the random generated number is duplicate or not. You just have to keep generating randomNumber until you find a unique random and then add it to the Set to prevent the duplicates.
Here is a quick code snippet:
public static void main(String[] args) {
String[] fruit = {"orange", "apple", "pear", "bannana", "strawberry", "mango"};
Random numberGenerator = new Random();
/* Generate A Random Number */
int nextRandom = numberGenerator.nextInt(6);
Set<Integer> validate = new HashSet<>();
/* Add First Randomly Genrated Number To Set */
validate.add(nextRandom);
for (int i = 0; i < 5; i++) {
/* Generate Randoms Till You Find A Unique Random Number */
while(validate.contains(nextRandom)) {
nextRandom = numberGenerator.nextInt(6);
}
/* Add Newly Found Random Number To Validate */
validate.add(nextRandom);
System.out.println(fruit[nextRandom]);
}
}
Output:
mango
apple
strawberry
pear
orange
You can wrap int into 'Interger' and add it to Set. Set holds no duplicates so there will be only unique values in it. So then just check if a Set already has given Integer with Set.contains(Integer).
my personal solution :
private static int[] randomIndexes(int len) {
int[] indexes = new int[len];
for (int i = 0; i < len; i++) {
indexes[i] = i;
}
for (int i = len - 1, j, t; i > 0; i--) {
j = RANDOM.nextInt(i);
t = indexes[j];
indexes[j] = indexes[i];
indexes[i] = t;
}
return indexes;
}
See it in action : https://gist.github.com/GautierLevert/a6881cff798e5f53b3fb
If I understand you correctly, then you want to choose n-1 elements at random from a list of n elements. If yes, then I recommend to choose just one at random and take all the others.
Arrays.shuffle(fruit);
int notThis = numberGenerator.nextInt(6);
for(int i = 0; i < fruit.length; i++)
if(i!=notThis) System.out.println(fruit[i]);
Copy your array into List<String>, then shuffle it, then just pick elements one by one:
List<String> copy = new ArrayList<>(Arrays.asList(fruit));
Collections.shuffle(copy);
for (String f : copy)
System.out.println(f);
I think it will be easier using an ArrayList, and also controlling the generation of the random number as shown below.
import java.util.Random;
public class QuestionOneA2 {
public static void main(String[] args) {
List<String> fruits = new ArrayList<>();
fruits.add("orange");
fruits.add("apple");
fruits.add("pear");
fruits.add("bannana");
fruits.add("strawberry");
fruits.add("mango");
Random numberGenerator = new Random();
int nextRandom;
for (int i = 0; i < 6 ; i++) {
nextRandom = numberGenerator.nextInt(6 - i);
System.out.println(fruits.get(nextRandom));
fruits.remove(nextRandom);
}
}
}
fruit.remove(fruit[nextRandom]);
Maybe, is it the remove sub-method?

Random Array Generator Java

I need to initialize an array of characters with 1000 random characters between [a,..z] and [A,..,Z].
I don’t want do this by first generating only characters between [a,..z] and then only characters in [A...Z] but treat all 52 characters equally.
I know one way to do this is to generate a random number between 0 and 51 and assign it one of the character values.
How would I approach this problem or assign values to the random numbers between 0 and 51?
You have got the interesting code idea.
Here might be the thought.
Take all the a-z and A-Z and store them in an array[].
Randomly generate a number between 1-52 (use API classes for that).
You will get a number in step 2, take it as an array index and pick this index from array[] of chars.
Place that picked char to your desired location/format............
Process it.
Best Regards.
Let me give you some general guidelines. The "one way to do this" you mentioned works. I recommend using a HashMap<E>. You can read more about hashmaps in the docs:
http://docs.oracle.com/javase/7/docs/api/java/util/HashMap.html
Alternatively, you can use another array that contains a - z and A - Z and you can use the index number to refer to them. But in this case I think it makes more sense to use a HashMap<E>.
I think you know how to create a Random object. But if you don't, check out the docs:
http://docs.oracle.com/javase/7/docs/api/java/util/Random.html
So you basically use the nextInt method of the Random class to generate a random number. And you can put that random number into your HashMap or array. And then you just put that character you get into an array that stores the result of the program.
This is the sample work, hope this will work for you
import java.util.ArrayList;
import java.util.Random;
public class RandomNumber {
public static void main(String args[]) {
char c;
ArrayList<Character> character = new ArrayList<Character>();
Random rn = new Random();
for (int i = 0; i < 500; ++i) {
character.add((char) (rn.nextInt(26) + 66));
character.add((char) (rn.nextInt(26) + 97));
}
System.out.println(character);
}
}
The simplest approach would be:
// constant declared in the class
static final int LETTERS_COUNT = 'z'-'a'+1;
char[] randomChars = new char[500];
Random r = new Random();
for(int i=0; i<randomChars.length; i++) {
randomChars[i] = (char)(r.nextInt(LETTERS_COUNT) + (r.nextBoolean() ? 'a' : 'A'));
}
If you don't like accessing random number generator two times, you can generate numbers from 0 to 51:
for(int i=0; i<randomChars.length; i++) {
int num = r.nextInt(LETTERS_COUNT*2);
randomChars[i] = (char)(num >= LETTERS_COUNT ? 'a'+(num-LETTERS_COUNT) : 'A'+num);
}
However I don't see any advantages of this approach. Internally r.nextInt may also change its internal state several times. The distribution should be similar in both cases.
You can this with a function using either arrays or arithemtic.
Note that you can calculate with characters like with numbers, because they are stored as numbers (http://www.asciitable.com/), you will also note that digits, small letters and big letters are stored in sequence so that accessing ranges is pretty easy with a simple for-loop.
private Random r = new Random();
public char randomLetter() {
int randomNumber = this.r.nextInt(52);
if(randomNumber >= 26) {
return (char)(('A'+randomNumber)-26);
} else {
return (char)('a'+randomNumber);
}
}
The version using an array will be faster, but can only be used if the set of possible outcomes is small enough to be stored.
private Random r = new Random();
private static char[] set = new char[52]; //static because we only need 1 overall
static { //this is a static "constructor"
for(int i = 0; i < 26; i++) {
set[i] = (char)('a'+i);
set[i+26] = (char)('A'+i);
}
}
public char fastRandomLetter() {
final int randomNumber = this.r.nextInt(52);
return set[randomNumber];
}
public class ShuffleArray {
public static void main(String[] args) {
int[] array = { 1, 2, 3, 4, 5, 6, 7 };
Random rand = new Random();
for (int i = 0; i < array.length; i++) {
int randomIndexToSwap = rand.nextInt(array.length);
int temp = array[randomIndexToSwap];
array[randomIndexToSwap] = array[i];
array[i] = temp;
}
System.out.println(Arrays.toString(array));
}
}

Why won't this create multiple sets of random numbers? [duplicate]

This question already has answers here:
Random Number Generator: mainly how to stop repetition of numbers. Java
(6 answers)
Closed 9 years ago.
Ok so the objective is to generate 6 random numbers per line/row. With x number of rows (set by the user via UserInput). Each row MUST have unique numbers (non-duplicated numbers). I'm pretty sure the numbers are unique, however I can't seem to get it to have multiple rows, and I cannot figure out for the life of me what part is preventing multiple rows.
package rtg;
import java.util.Arrays;
import java.util.HashSet;
import java.util.Random;
import java.util.Set;
public class Array {
public static void main(String[] args) {
String name;
int noTickets;
int[] numbers = new int[6];
Set<Integer> randomNumbers = new HashSet<>();
Random rand = new Random();
int ticketCount = 1;
System.out.println("Please input your name");
name = UserInput.readString();
System.out.println("Please input the number of tickets you want");
noTickets = UserInput.readInt();
System.out.println("___________________________________________\n___________________________________________");
System.out.println("___________________________________________\n___________________________________________");
System.out.println("Name: " +name+ "\nNumber of Tickets: " +noTickets+ "\nNumbers: ");
for (ticketCount = 1; ticketCount <= noTickets; ++ticketCount){
while (randomNumbers.size() < 6) {
randomNumbers.add(rand.nextInt(50) + 1);
}
int i = 0;
for (Integer n : randomNumbers) {
numbers[i++] = n;
}
System.out.print( Arrays.toString(numbers) + "\n");
}
}
}
EDIT Thanks a lot everyone, I finally got there, turns out I put the array in the wrong place (it was outside the for loop so only made 1 set of random numbers) Fixed it now. Next challange; having a comparison program to scan 90+ sets of 6 unique numbers, and comparing if any of them match a different set (per row/set >.<)
You can stuff random integers into a Set<Integer> until it has six elements:
Set<Integer> randomNumbers = new HashSet<>();
Random rand = new Random();
while (randomNumbers.size() < 6) {
randomNumbers.add(rand.nextInt(50) + 1);
}
Alternatively, you can generate the numbers 1-50, shuffle them, and pick any six elements:
List<Integer> numbers = new ArrayList<>(50); // known capacity
for (int i = 1; i <= 50; ++i) { numbers.add(i); }
Collections.shuffle(numbers);
List<Integer> sixRandomNumbers = numbers.subList(0, 6);
The first solution does extra work whenever there is a collision; this extra work goes up the greater the ratio is of desired to total numbers. The second does extra work by having to deal with all 50 numbers; the extra work goes down the greater the ratio is of desired to total numbers. It's an interesting question where the cross-over point is.
EDIT (Responding to the edit to the original question) After you use one of the above methods to generate six distinct, random numbers, you need to put them into the variables you are going to use. One way (say, using the first method) is as follows:
int[] numbers = new int[6];
Set<Integer> randomNumbers = new HashSet<>();
Random rand = new Random();
while (randomNumbers.size() < 6) {
randomNumbers.add(rand.nextInt(50) + 1);
}
System.out.println("Six random numbers: " + randomNumbers.toString());
// if you need them as an `int` array:
int i = 0;
for (Integer n : randomNumbers) {
numbers[i++] = n;
}
The numbers array replaces your variables number1, ..., number6.
Use a data type which allows you to check if the int has already been created. For example, adding them to an ArrayList<Integer>.
ArrayList<Integer> numbers = new ArrayList<Integer>();
while(numbers.size() < 6) {
int num = rand.nextInt(50) + 1;
if(!numbers.contains(num)) {
numbers.add(num);
}
}
Of course, as #sanbhat says in the comments, you can use a Set<Integer> and avoid the if() conditional entirely in the loop. However I thought this would be more intuitive for a beginner who doesn't know that the Set API will not add a duplicate element.
Save a sorted list or more efficiently a set of the previously chosen values and check your current selection against the previous ones, if it was previously chosen try again.
If you know the valid range of your random numbers and if the size of that range is not prohibitive, one simple algorithm would be as follows:
Create an array with a size equal to your number range
Consecutively fill your array with the numbers in your number range
Iterate through the list an arbitrarily large number of times; generate two pseudorandom numbers that are within your array indices, and swap the two elements at those indices
After the iteration is complete, you will have an array of uniquely represented numbers that are all within your number range that appear in a random order. This nearly exactly simulates what happens when one shuffles a deck of cards.
You can then write a simple method to consecutively pop numbers out of your array each time it is called.
An advantage of this algorithm is that it can be implemented as an array of primitives, eg. int[], without any need for the Java Collections API.

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