I have a question regarding the following code
Random randomGenerator = new Random();
int randomInt = randomGenerator.nextInt(4);
String wordList[] = new String[4];
{
wordList[0] = "Red";
wordList[1] = "Blue";
wordList[2] = "Green";
wordList[3] = "Orange";
}
String wordToDisplay = wordList[randomInt];
This code works fine however I would like to know if it was possible to get it to not pick the same word two times in a row. For example, if it just selected "Red" then it would not pick "Red" again the next consecutive time. I read something about DISTINCT but I'm not sure if that's along the right path.
Here is the code for the button which uses this
final Button button1 = (Button) findViewById(R.id.button1);
final TextView textView = (TextView) findViewById(R.id.text_random_text);
button1.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// Perform action on click
Random randomGenerator = new Random();
int randomInt = randomGenerator.nextInt(9);
String wordToDisplay = wordList[randomInt];
textView.setText(wordToDisplay);
Thankyou for your help
go for list and remove color once used:
private static ArrayList<String> arrayList = new ArrayList<String>();
private static Random random = new Random();
public static void fillList(){
arrayList.add("Red");
arrayList.add("Blue");
arrayList.add("Green");
arrayList.add("Orange");
}
public static String getNextRandomColor(){
if(arrayList.isEmpty()){
fillList();
}
return arrayList.remove(random.nextInt(arrayList.size()));
}
You can do this in two way (probably more but two that I can think of right now):
1) Create a function that uses a global variable to store the last generated random number.
It will look something like this:
int myRand(int i) {
int aux;
Random randomGenerator = new Random();
do {
aux = randomGenerator.nextInt(i);
} while (aux != lastRandGenerated);
lastRandGenerated = aux;
return aux;
}
, where lastRandGenerated is a global variable that you initialize to 0.
Then you use this function to generate random numbers.
2) You can create a class that has a function very similar to the one above and then instantiate an object of that class and use that to generate your random numbers. In the class create a static variable that will remember the last generated random number. Use that instead of the global variable.
The specifics are a bit out of my league but as a math problem there are 24 combinations (4 * 3 * 2 * 1). As heavy handed as this might sound, worst case you could work out all the combos and then pick a one out of 24 random.
Related
I need random number in recyclerView adapter but I am unable to get any. I am trying to generate the number in the Activity.java and pass it in the constructor but I am getting same number on every item. I have tried this :
Random random = new Random();
randInt = random.nextInt(6);
adapterPost = new AdapterPost(QuestionsActivity.this, postList, randInt);
//Adapter
public class AdapterPost extends RecyclerView.Adapter<AdapterPost.ViewHolder> {
Context context;
ArrayList<ModelPost> postList;
String myUid;
DatabaseReference likesRef;
DatabaseReference postRef;
boolean hasLiked = false;
int randInt;
public AdapterPost(Context context, ArrayList<ModelPost> postList, int randInt) {
this.context = context;
this.postList = postList;
this.randInt = randInt;
myUid = FirebaseAuth.getInstance().getCurrentUser().getUid();
likesRef = FirebaseDatabase.getInstance().getReference("Likes");
postRef = FirebaseDatabase.getInstance().getReference("Posts");
}
Please let me know how can I get a different random number on evey item. Thanks!
You need to create list of unique random numbers having same size which your postList have.
public void generateRandom(){
Random random = new Random();
int randInt = random.nextInt(postList.size());
while(list_rand.size()!=postList.size()) {
if (list_rand.contains(randInt)) {
generateRandom();
} else {
list_rand.add(randInt);
}
}
}
Now call generateRandom method and pass populated list to adapter like this:
ArrayList<Integer> list_rand = new ArrayList(postList.size);
generateRandom()
adapterPost = new AdapterPost(QuestionsActivity.this, postList,list_rand);
Now you have unique random numbers according to your listview size. Now you can set items on your listview item freely because every item in list_rand is unique random number.
I am trying to generate the number in the Activity.java and pass it in the constructor but I am getting same number on every item.
Emphasis mine. Of course you're getting the same number on every item since - based on your code - you are generating one random number and using it for the one adapter which creates all of your items.
If you want a different number for each item, generate a new number for each item. For example, you could set a random value on each model item before passing it to the adapter.
Random random = new Random();
for (item in postList) {
item.setRandomNumber(random.nextInt(6));
}
adapterPost = new AdapterPost(QuestionsActivity.this, postList);
Try with the following code and generate random number in specific range.
int minVal = 50;
int maxVal = 200;
Random r = new Random();
int randomVal = r.nextInt(maxVal - minVal + 1) + minVal;
I want my program to ask random questions and have dynamic answers But it only asks random questions and I need a dynamic answer
Button btn_1,btn_2;
TextView text;
setContentView(R.layout.activity_main);
btn_1=findViewById(R.id.btn_1);
btn_2=findViewById(R.id.btn_2);
text=findViewById(R.id.text);
int min = 1;
int max = 3;
Random r = new Random();
int rand = r.nextInt(max - min + 1) + min;
String[]question={"What is Name Color Sky ?",
"What is Name Color Night?",
"What is Blood Color?"
};
String[]answer={"Blue ",
"Black",
"White",
"Red",
"Green"
,"Purple"
};
text.setText(question[rand]); }
Screen
Try this:
btn_1.setText(answer[r.nextInt(6)])
btn_2.setText(answer[r.nextInt(6)])
This will choose 2 random colours independently.
Edit
To ensure that the correct answer is available, you will need to store the correct answers somewhere. I strongly recommend making a Question class that stores the string for the question and the correct answer, but you can achieve the desired effect with just an array of the answers, e.g.:
Button[] answerButtons = new Button[] {btn1, btn2};
int numButtons = 2;
String[] correctAnswers = new String[] {"Blue", "Black", "Red"}; // you have a space after blue, remove it
List<String> answersDisplayed = Arrays.asList(new String[numButtons]);
int indexOfCorrectAnswer = random.nextInt(numButtons);
answersDisplayed.set(indexOfCorrectAnswer, correctAnswers[rand]); // the number used to pick the question earlier
for (int i = 0; i < numButtons; i++){
if (correctAnswers[rand] == null) {
// rand was used to pick the question, so pick the answer that goes with it
// pick a random answer that hasn't come up yet
String incorrectAnswer = answer[random.nextInt(6)];
while (answersDisplayed.contains(incorrectAnswer)){
incorrectAnswer = answer[random.nextInt(6)];
}
answersDisplayed.set(i, incorrectAnswer);
}
answerButtons[i].setText(answersDisplayed.get(i));
}
This will work for any number of buttons
I want to get the product of the inputted values in two editTexts.
For example I will input [1,2,3,4,5] in xValues then I will input also [6,7,8,9,10] in freqValues then it will multiply (1*6),(2*7),(3*8),(4*9),(5*10). How will i do that? Please help me. Thank you in advance:)
final AutoCompleteTextView xValues = (AutoCompleteTextView) findViewById(R.id.x_Values);
final AutoCompleteTextView freqValues = (AutoCompleteTextView) findViewById(R.id.frequency_Values);
Button btnCalculate = (Button) findViewById(R.id.btncalculate);
btnCalculate.setOnClickListener(new OnClickListener(){
public void onClick(View arg0)
{
String[]x = ( xValues.getText().toString().split(","));
String []freq = ( freqValues.getText().toString().split(","));
int[]convertedx=new int[x.length];
int[]convertedfreq=new int[freq.length];
}
});
You'll have to do some error catching to make sure only numbers are inputted but once you get that figured out, do something like this:
...
String[]x = ( xValues.getText().toString().split(","));
String []freq = ( freqValues.getText().toString().split(","));
int product = 0;
for(int i = 0; i < x.length(); i++) {
int tempX = Integer.parseInt(x[i]);
int tempFreq = Integer.parseInt(freq[i]);
product += (tempX * tempFreq);
}
Assuming that the arrays are split correctly and only contain integers, this loop will grab the first int from X[] and Freq[] and then multiply them together, and add it to product, then grab the 2nd int from these arrays, parse the string into an int, and then multiply those and loop through until the end of the array.
I'm trying to set up my activity so that I can generate a set of random numbers from methods outside of my onCreate method. Here's how my activity is set up...
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
this.optionOne();
this.optionTwo();
this.optionThree();
}
public void optionOne() {
// generate a random number here
int random = Math.random();
// generate more random numbers and do more stuff here
}
The problem is, any random numbers I generate outside of the onCreate method are considered 'static' and the numbers are always 0. If I generate numbers inside the onCreate method, it of course works just fine. How can I fix this?
private static Random ranGenerator=new Random();
Declare it as a member of the class.
then just call ranGenerator.nextInt() any time to get it.
To generate random number use,this will create random between specific range
public void optionOne() {
var=(int)(Math.random() * (max - min) + min) //math.random will return integer values
// use your var wisely
}
use
Random rand = new Random();
int random = rand.nextInt();
or
int random = rand.nextInt(range);
According to doc here
Math.random() Returns a pseudo-random double n, where n >= 0.0 && n < 1.0.
This will help you to create an array list of non repeating random numbers
ArrayList<Integer> indexArray = new ArrayList<Integer>();
for (i = 0; i < 202; ++i) {
number.add(i);
// number.add(num);
}
Collections.shuffle(number);
Using the text to speech API I want to change the string array to increment from index 0 string and when it reaches the end it will go back to the beginning.
At the moment it uses a random generator and the method works as follows:
public static void sayHello() {
// Select a random hello.
int helloLength = HELLOS.length;
String hello = HELLOS[RANDOM.nextInt(helloLength)];
mTts.speak(hello,
TextToSpeech.QUEUE_FLUSH, // Drop all pending entries in the playback queue.
null);
}
HELLOS is the array and it holds the strings:
String [] HELLOS = {"One" "Two" "Three" "Four"};
Appreciate any help
Thanks.
When you want to increment an index but loop around to zero again modulo is your friend.
int currentHelloIndex = 0;
public static void sayHello() {
// Select a random hello.
int helloLength = HELLOS.length;
String hello = HELLOS[currentHelloIndex];
currentHelloIndex = (currentHelloIndex + 1) % helloLength;
mTts.speak(hello,
TextToSpeech.QUEUE_FLUSH, // Drop all pending entries in the playback queue.
null);
}