Need help randomizing images and not repeat throughout activity - java

I have a simple educational kids game with 7 questions. One imageView and four buttons for each question, the user must match the correct answer(button) with what is shown in the image view. I want the images(questions) to be random every game but never repeat a question during a game until all 7 have been asked. I am only using 3 images as of now just to get it working.
Option 1
int[] res = {R.drawable.img1, R.drawable.img2, R.drawable.img3};
Method
private void randomImage() {
Random rand = new Random();
int rndInt = rand.nextInt(res .length);
imgView.setImageDrawable(getResources().getDrawable(res[rndInt]));
}
Option 2
private ArrayList<Integer> res1 = new ArrayList<Integer>();
res1.add(R.drawable.img1);
res1.add(R.drawable.img2);
res1.add(R.drawable.img3);
Method
private void randomImage1() {
Collections.shuffle(res1);
for(int i=0;i<res1.size();i++){
imgView.setImageResource(res1.get(i));
}
}
Both of these work for randomizing, but I am having a little trouble figuring out how to check if an image has already appeared and to correct it if it had.
In fact I'm not really quite sure where to start. Any help would be appreciated.

If you dont want to see repeated items from array then use shuffleArray() like this example and for a list use shuffle(list) like this example2

Related

How to use randomization, so when you press a button it brings you to a random screen

I have searched for an answer to this question with my time in my Computer Science lab. We are using Android Studio for this app.
What I want to do is to use randomization to make a set of screens be randomized when you click a button. My duo is working on a dice rolling app, and we had the idea to make six different screens for each of the sides of the die. Basically, when we click the button to "roll the dice", it think for a second, then brings you to a random page with a picture of the number on the die which you got.
This is incredibly weird, and I have searched for at least 3 hours straight for a solution to this problem but to no avail. If anybody needs more information on the problem (because I do not know how to properly phrase it), then just ask me.
Just use Random.nextInt() to get a random number up to 6, and use that to choose one image of the 6 for each die side. You do not need to create 6 different screens, you just need 6 different images where the number indicates which image to use. For example:
// A list of drawables you've defined in /res/drawable folder for each die side
final int[] images = new int[6] {
R.drawable.die_side_1,
R.drawable.die_side_2,
R.drawable.die_side_3,
R.drawable.die_side_4,
R.drawable.die_side_5,
R.drawable.die_side_6
};
int random = Random.nextInt(6); // Get random value, 0-5
int dieSideDrawable = images[random]; // Pick image to show based on random value
mDieImageView.setImageResource(dieSideDrawable); // Show image on an image view
Hope that helps!
The easiest way to do exactly what you want would be to put the Activities in an Array, and select by using the Random class' nextInt method to choose the appropriate activity from the Array.
That being said, most likely you want to create a single activity with two images, and instead of selecting an activity or Fragment to show, you'd select the images you'd load into the Activity.
I would recommend using Fragments to achieve this.
create a list of fragments
ArrayList<Fragment> fragmentList = new ArrayList<>();
Now use the java Random class to generate the random number.
Random rand = new Random();
int n = rand.nextInt(fragmentList.size());
then just show that fragment.
getSupportFragmentManager()
.beginTransaction()
.replace(containerViewId, fragmentList.get(n))
.addToBackStack(null)
.commit();
Using multiple activities seems unnecessary here (and will significantly slow down your app). If you want to show a different image based on the result of a random number that's been generated, then just .setImageResource() for your Image View based on the result of that random number.
In the example below I separated the random number generation (the generateRandomInt() method which stores a random integer in the thisRoll variable) and only called it when the changeImageView() method runs onClick.
public void changeImageView(View view){
generateRandomInt();
if (thisRoll == 1) {
mainImage.setImageResource(R.drawable.s1);
} else if (thisRoll == 2) {
mainImage.setImageResource(R.drawable.s2);
} else if (thisRoll == 3) {
mainImage.setImageResource(R.drawable.s3);
} else if (thisRoll == 4) {
mainImage.setImageResource(R.drawable.s4);
} else if (thisRoll == 5) {
mainImage.setImageResource(R.drawable.s5);
} else {
mainImage.setImageResource(R.drawable.s6);
}
Toast.makeText(DiceRollActivity.this, thisRoll + " ...But The House Always Wins!", Toast.LENGTH_SHORT).show();
}

Print random key followed by specific value? [duplicate]

This question already has answers here:
How do I efficiently iterate over each entry in a Java Map?
(46 answers)
Closed 4 years ago.
I'm pretty new to Java and in an effort to learn more I'm trying to make a game whereby you're given a random lyric from a song, and then the song title and artist.
This would be pretty easy, however I wanted the lyric to be random, and then print the artist and song title using a seperate method. My problem is that I'm not sure how to go from printing one random string to printing a specific answer.
I currently have the lyrics and the answers in a hashmap with the lyrics as keys and answers as values, and can print random keys by turning them into an arraylist using this method
public void randomLyrics()
{
ArrayList<String> lyricKey = new ArrayList<String>(lyrics.keySet());
if(lyrics.size() > 0) {
Random rand = new Random();
int index = rand.nextInt(lyrics.size());
System.out.println(lyricKey.get(rand.nextInt(lyrics.size())));
}
}
however I'm pretty sure that this isn't the right way to go about it, and am not sure how I would go about printing the answers seperately.
Any help would be much appreciated.
Also just to clarify, I want to call a method (randomLyrics) which will display a random lyric such as "that's me in the corner, that's me in the spotlight" and then call a seperate method (answer) which would then print "Losing My Religion - R.E.M."
Many thanks
Here is full example run this program multiple times you will get some random value:-
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Random;
public class HashM {
public static void main(String[] args) {
HashMap<String, String> lyrics = new HashMap<>();
// KEY :- Lyrics AND Value is Album Name
lyrics.put("that's me in the corner, that's me in the spotlight", "Losing My Religion - R.E.M.");
lyrics.put("I will try not to breathe I can hold my head still with my hands at my knees",
"Automatic for the People");
lyrics.put("Eu não aturo mais Sou um trator", "É Duda Brack");
randomLyrics(lyrics);
}
public static void randomLyrics(HashMap<String, String> lyrics) {
ArrayList<String> lyricKey = new ArrayList<String>(lyrics.keySet());
if (lyrics.size() > 0) {
Random rand = new Random();
int index = rand.nextInt(lyrics.size());
System.out.println("###::####Your Random Number is :-" + rand.nextInt(lyrics.size()));
System.out.println(lyricKey.get(rand.nextInt(lyrics.size())));
}
}
}

Try on Making A Random sudoku 3x3 on Java - BlueJ

iam newbie in this so i will ask straightly and if smb can help me that would be appreciated. Iam trying to make a Sudoku Game in BlueJ and until now i havent got any help from google searches and staff so iam posting here.
I need my sudoku firstly to be a random puzzle when pressing a button to start new.
Then the main concept and correct me if iam wrong is to built one random table which will be the solution for the user and one table where user can see 3 numbers only from the table and pick the other. With Comparing of 2 tables, users and solution the programm can see if the user has it correct.
Until now i have this code.
import java.awt.*;
import javax.swing.*;
import java.util.*;
public class MyFrame extends Frame
{
private double[] data;
private Button avgButton,minButton,maxButton,rndomButton;
private Button quit;
public MyFrame(String title)
{
super(title);
resize(200,200);
setResizable(false);
setLayout(new GridLayout(3,2));
quit=new Button("QUIT");
rndomButton=new Button("RANDOM");
add(rndomButton);
add(quit);
}
public int Array()
{
Random rand = new Random();
int n = rand.nextInt(3) + 1;
int y = rand.nextInt(2) + 1;
int i=0;
int j=0;
int value;
int[][] board = new int[3][3];
value=board[0][0];
int z=board[0][0];
for(i=0;i<3;i++)
{
do{
board[i][0]=n;
}while (board[i][0]!=board[i-1][0]&&board[i][0]!=board[i-2][0]);
}
for(j=0;j<3;j++)
{
do{
board[0][j]=n;
}while (board[0][j]!=board[0][j-1]&&board[0][j]!=board[0][j-2]);
}
for(i=1;i<3;i++)
{
for(j=1;j<3;j++)
{
do{
board[i][j]=n;
}while (board[i][j]!=board[i-1][j]&&board[i][j]!=board[i-2][j]&&board[i][j]!=board[i][j-1]&&board[i][j]!=board[i][j-2]);
}
}
for(i=0;i<3;i++)
{
for(j=0;j<3;j++)
{
z=board[i][j];
}
}
return z;
}
public boolean action(Event evt,Object arg)
{
if(evt.target.equals(rndomButton))
message("Array: "+Array());
else
if(evt.target.equals(quit))
System.exit(0);
return true;
}
}
I dont know if it is correct because when i try to return z value its just a window pops up with nothing in there.
Note if i get return z in lasts for i get an error on bluej.
Sorry for my programming skills.
I hope u can help me or at least recommend me some links to look at.
Thanks in advance.
It's possible you've jumped into your coding a little too soon. It appears that you need to better define your approach to the problem. First, think about how you would solve it by hand. Break that down into steps, and write those steps down. Then, make your code model your solution step by step.
For example, if you think about building your board one row at a time, then you would write down something like, "For the first row, take 1, 2, 3, and rearrange them in random order..." If you think. instead, about building your board one digit at a time, you might write, "Place a 1 in a random location in the first row. Place a 1 in a random location in the second row, but avoid a conflict with the first row. Place a 1 in the only remaining column in the third row.
With your second digit, you'll encounter more constraints-- instead of just selecting any column at random from the first row, you'll need to select randomly from an available column.
1 2 .
. 1 .
. . 1
In the example above, when placing a 2 in your second row, how do you determine which is available? (One choice leads to a solution, the other to a dead-end). Once you're able to articulate the steps you would take to solve the problem by hand, writing the code becomes much easier and the small pieces you may get stuck on become easier to address.

Generate multiple draws (calls) of a given method in java (simulated lottery)

I received the task of simulating a lottery draw in java. The program skeleton yields the method generateOneDraw, which creates 6 random numbers between 1 and 49
static int[] generateOneDraw() {
int numbers[] = new int[NUMBER_OF_ELEMENT_PER_DRAW];
for(int i=0; i<numbers.length; ++i) {
int nextNumber;
do {
nextNumber = generateNextRandomNumber();
} while(numberIsInArray(nextNumber, numbers));
numbers[i] = nextNumber;
}
return numbers;
}
We are then required to implement a function that simulates the lottery draw over 5 weeks and stores them in the variable draws. I believe this should be done over a two-dimensional array. Am I right in this way of thinking? Any pointers on implementing it would be greatly appreciated.
static void generateAllDraws()
Thanks in advance.
EDIT: Nevermind, I did it with a simple two dimensional array and it worked.
Since this seems like home work, I will not go into much detail but you can either:
Create a 2 dimensional list, as per your initial reasoning;
Create a Draw class which represents a lotto draw, and create multiple instances of this class. Each Draw class could have a Date which would denote when did the draw take place.
Both approaches should work, the second approach is a little more object oriented.

Changing a buttons background image through using a random array

OK so I'm trying to get this button on its second click to display an image. I have 8 images for it to choose from and I want it to select it randomly. I set up an array with all of the R.drawable.img in the string and i tried placing it inside of this
else if (click == 1)
{
rpic = generator.nextInt(ppic);
spinntoke.setBackgroundResource(R.pic[rpic]);
}
So it is not allowing me to do that. Any ideas as to how i can get the random generator to select 1 of those 8 pictures at random when it is clicked? Thanks
You have not really provided enough info but here is what I imagine you would do.
have an array int[] that looks like this: [R.drawable.img1, R.drawable.img2, R.drawable.img3]
in onClick(): random = some random between 0 and array.size()-1;
spinntoke.setBackgroundResource(array[random]);
This way you have an array of ints (your R resources) where you can pick a random one. Don't forget to make your random generator only generate numbers from 0 to the array size-1.
Edit: code:
Random randomGenerator = new Random();
int random = randomGenerator.nextInt(array.size());
spinntoke.setBackgroundResource(array[random]);
You probably want to look at drawableLeft property - or one of the others - rather than the background.

Categories