Please help me to random it without repeat element. - java

This below code it was run by repeat the same elements,
what i want is to random it without repeat.
public class khmerAlphabetExercise extends Activity {
AlphabetData data;
MediaPlayer mp;
int dataType;
int dataKey;
Random random;
private ImageView iv1, iv2, iv3,iv4;
private ImageView[] imgs = { iv1, iv3, iv3,iv4 };
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_khmer_exercise);
int[] imageViews={R.id.ex_con1,R.id.ex_con2,R.id.ex_con3,R.id.ex_con4};
//int images[]={R.drawable.con_ex_01,R.drawable.con_ex_02,R.drawable.con_ex_03,R.drawable.con_ex_04,R.drawable.con_ex_05,R.drawable.con_ex_06,R.drawable.con_ex_07,R.drawable.con_ex_08,R.drawable.con_ex_09,R.drawable.con_ex_10};
int[] images={data.getImageId()};
random = new Random(System.currentTimeMillis());
for(int v : imageViews)
{
ImageView iv = (ImageView)findViewById(v);
iv.setImageResource(images[random.nextInt(images.length)]);
}
}
}

You could keep a counter of the images left to select. And everytime you choose one you swap it in the original array with the last unselected.
So, for example, you have an array {0,1,2,3,4}. The Length of unselected will be 5, lets call it l
Choose a random number n between 0 an l-1
Your new element is the element at n.
Swap the element at n with the element at l-1, substract one to l and go back to point 1 if l bigger than 0. Go to point 4 if l == 0.
You finish

You can use Collections.shuffle
Collections.shuffle(Arrays.asList(images));
then you can just add this images one by one using a simple for loop without randomizing positions. BTW in your example images contains only one element..

Related

the app keep crashing whenever the While loop starts

I have made an ArrayList store the numbers from 1 to 10 in Strings, then I wanted to make the numbers in the ArrayList displayed in the screen using While loop. But the app keeps crashing when the loop starts.`
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_number);
}
ArrayList<String> words = new ArrayList<>();
{
// Create an ArrayList of words
words.add("One");
words.add("Two");
words.add("Three");
words.add("Four");
words.add("Five");
words.add("Six");
words.add("Seven");
words.add("Eight");
words.add("Nine");
words.add("Ten");
LinearLayout rootView = findViewById(R.id.rootView);
// Create a variable to keep track of the current index position
int index = 0;
// Keep looping until we've reached the end of the list (which means keep looping
// as long as the current index position is less than the length of the list)
while (index < words.size()) {
// Create a new TextView
TextView wordView = new TextView(this);
// Set the text to be word at the current index
wordView.setText(words.get(index));
// Add this TextView as another child to the root view of this layout
rootView.addView(wordView);
// Increment the index variable by 1
index++;
}
}
The initialisation is called before the onCreate method. so the views are not created yet.
ArrayList<String> words = new ArrayList<>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_number);
// Create an ArrayList of words
words.add("One");
words.add("Two");
words.add("Three");
words.add("Four");
words.add("Five");
words.add("Six");
words.add("Seven");
words.add("Eight");
words.add("Nine");
words.add("Ten");
LinearLayout rootView = findViewById(R.id.rootView);
// Create a variable to keep track of the current index position
int index = 0;
// Keep looping until we've reached the end of the list (which means keep looping
// as long as the current index position is less than the length of the list)
while (index < words.size()) {
// Create a new TextView
TextView wordView = new TextView(this);
// Set the text to be word at the current index
wordView.setText(words.get(index));
// Add this TextView as another child to the root view of this layout
rootView.addView(wordView);
// Increment the index variable by 1
index++;
}
}
You are writing this code outside your onCreate function. Put all the code from Array List to index++ inside onCreate function, so when activity is created, it is inside the content.

How to setText on the ArrayList of Button in Android

I am making a random number generator app in this app we will take the random number range like 0-100 then when we click on the generate button it will set the number on the button.
Manually we can set that value of random number and set it on button. If i set the random number 4 will always correct it means the fourth button will always be correct.
Now I want to make the shuffle of random number on button so I create the Random number Array and ArrayList of button so I add it on the ArrayList but I don't know how to set the value of random number array on arraylist of button.
If there is an other way to solve this problem then guide me.
public class MainActivity extends AppCompatActivity {
Button genbtn,optbtn1,optbtn2,optbtn3,optbtn4;
EditText mintext,maxtext;
Random rand[]=new Random[4];
int minrange,maxrange;
ArrayList <Button>shufflearray=new ArrayList<Button>();
int random[]=new int[4];
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
genbtn=(Button)findViewById(R.id.gen);
shufflearray.add((Button)findViewById(R.id.opt1));
shufflearray.add((Button)findViewById(R.id.opt2));
shufflearray.add((Button)findViewById(R.id.opt3));
shufflearray.add((Button)findViewById(R.id.opt4));
mintext=(EditText)findViewById(R.id.min);
maxtext=(EditText)findViewById(R.id.max);
genbtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
minrange=Integer.parseInt(mintext.getText().toString());
maxrange=Integer.parseInt(maxtext.getText().toString());
for(int i=0;i<rand.length;i++){
random[i]=rand[i].nextInt(maxrange-minrange)+maxrange;
}
for(int i=0;i<shufflearray.size();i++) {
}
}
});
}
You can use Random function like this .
int rand = (int)(Math.random());
it will give you a random number which you can pass to the array list .

how to override the position of an onItemClick in Android

So I have a button, and this button switches the cell of a listview with the cell above, and vise versa for ANOTHER button which is for down (this one is for up... It doesn't matter which, I just decided to talk about this one). The whole button and list view thing is working, but my problem is when I press the up button, and then decide to press it again, it just acts as a down button. The reason for this is because it's still stuck on the same item/position of the list view, and I need to figure out a way to Override the position of the onItemClick in the code??
```
upButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//upButton onClick
Integer myTeam = position; //7 -159
Integer otherTeam = position - 1; //6 - 1678
Map<Integer, String> onClickMap = sortByValue(Constants.picklistMap);
String extraValue;
Log.e("myposition", myTeam.toString());
Log.e("otherposition", otherTeam.toString());
extraValue = onClickMap.get(myTeam); //159
String team = onClickMap.get(otherTeam);
Constants.picklistMap.put(myTeam, onClickMap.get(otherTeam));
Constants.picklistMap.put(otherTeam, extraValue); //6
Log.e("Position: ",Constants.picklistMap.get(position));
Log.e("Position - 1: ",Constants.picklistMap.get(position - 1));
if(myTeam != 0) {
dref.child("picklist").child(myTeam.toString()).setValue(Integer.parseInt(Constants.picklistMap.get(myTeam)));
dref.child("picklist").child(otherTeam.toString()).setValue(Integer.parseInt(Constants.picklistMap.get(otherTeam)));
} else {
Toast.makeText(getActivity(), "Nice try.
If you try it again, the app is going to crash as punishment ... (:",
Toast.LENGTH_LONG).show();
}
}
});
```
By overriding the position, I just mean how
position =+ 1
would make position = position + 1 in python, and I want to do the same thing in Java. The problem is I know that can't be done using the snippet of code I just used to increment the value of position!
Please help!
The reason I can't use position = position + 1 is because on the onItemClick, int position is defined, and then the onClick is created for the buttons, so I need position to be final for me to use it in the onClick, and if I got rid of final, i wouldn't be able to use it in the onClick as it can't be accessed from within an inner class when it's not final
Define which position you want to change, and use this method to update position. You can use this method in onClickListener. This should work.
private int position = 0;
private void up(ArrayList<Integer> arr){
if (position < 1 || position >= arr.size()) return;
int temp = arr.get(position - 1);
arr.set(position - 1, arr.get(position));
arr.set(position, temp);
position --;
}

JButtons and Mouse Listeners or Action Listeners

I am making a little game of math, which consists of creating a random numbered sequence of numbers between 1-9 or 10-99, then separating the number > 10 and then create a sequence out of it. Example, I have 4 numbers to generate, I generate 1, 3, 5, 10. Then I separate the number 10 and concatenate the numbers together like this : 1 3 5 1 0. Now the objective of the game is to reassemble the numbers together to get the sum. So I'd have to click 1, 3, 5, then 1 and 0 while keeping the mouse pressed to obtain 10. Finally I check the sum pressed in with the original sum to find if it's the right answer.
Anyways, I have some trouble with the MouseEvent and the buttons. First I created the numbers randomly, then put them in an int array. After that, I take that array and switch it into a String so I can put them on a Button. Then, when I create my button, I get the String and I do a String.charAt(i) to get a single digit of my sequence. I add my MouseListener on the button and then add my button to the panel.
I would like to get the value of the digit on my button when I press that button. I tried getSource(), getText() or other methods, but it didn't work. Should I use ActionListener for this or MouseListener?
Here's some snippet of my code:
fixedSequence is the String version of the number sequence
GameLogic is the class where I do the logic of the game
sequencePanel is the JPanel that shows the buttons of the sequence
Creating the int array sequence:
private void createSequence(int cutNumber) {
//cutNumber is the number of digits in my sequence
for(int i = 0; i < cutNumber; i++) {
numberSequence[i] = numberGenerator();
}
}
Creating the String array out of my int array:
private void sequenceToString() {
StringBuilder builder = new StringBuilder();
for(int value: numberSequence) {
builder.append(value);
}
fixedSequence = builder.toString();
}
Now to create the sequence with buttons:
private void createASequenceButton(char c, Container container) {
JButton button = new JButton(String.valueOf(c));
button.setAlignmentX(LEFT_ALIGNMENT);
button.addMouseListener(new SequenceButtonListener());
container.add(button);
}
private void addNumberSequence() {
//GameLogic is where I create the number sequence and where I do the
//logic of the game
for(int i=0; i < GameLogic.getFixedSequence().length(); i++) {
createASequenceButton(GameLogic.getFixedSequence().charAt(i),
sequencePanel);
}
}
Now for the MouseListener part:
private class SequenceButtonListener implements MouseListener {
public void mousePressed(MouseEvent event) {
//This is where I want to get the value in int or string of
//the button I pressed so I can do my calculation with it
}
}
I'd like some opinion on the way I did it, if I could do it an easier way or it's only possible with ActionListener instead of MouseListener.
Thank you for your time,
Carl

How to make a Random Layout when button clicked

Actually i want to make it Random class but then i think to much activity can make the app slow so i just want to make Relative layout Random
so i have 5 layout in one activity class
layout1 = (RelativeLayout)findViewById(R.id.layout1);
layout2 = (RelativeLayout)findViewById(R.id.layout2);
layout3 = (RelativeLayout)findViewById(R.id.layout3);
layout4 = (RelativeLayout)findViewById(R.id.layout4);
layout5 = (RelativeLayout)findViewById(R.id.layout5);
and in each layout there is the button in there to make layout random again
button.setOnClickListener(new View.OnClickListener() {
public void onClick(View v){
//The code to how make layout random
}
});
}
and then how to make layout that already opened not open again if the button random was pressed? then if all layout was already opened it will open new activity class
can anyone help me explain with give some example code of that?
Initially set visibility gone to all relative layouts and put all of them into View's ArrayList.
Get random number from 0 to List size.
Get View at random position and set its visibility to Visible and remove from ArrayList.
Do same thing until ArrayList is empty.
Create new activity when ArrayList is empty.
Code:
ArrayList<View> viewList=new ArrayList<>();
initLayouts(){
layout1 = (RelativeLayout)findViewById(R.id.layout1);
layout2 = (RelativeLayout)findViewById(R.id.layout2);
layout3 = (RelativeLayout)findViewById(R.id.layout3);
layout4 = (RelativeLayout)findViewById(R.id.layout4);
layout5 = (RelativeLayout)findViewById(R.id.layout5);
viewList.add(layout1);
viewList.add(layout2);
viewList.add(layout3);
viewList.add(layout4);
viewList.add(layout5);
for(int i=0;i<viewList.size();i++){
viewList.get(i).setVisibility(View.GONE);
}
button.setOnClickListener(new View.OnClickListener() {
public void onClick(View v){
loadRandomLayout();
}
});
}
public loadRandomLayout(){
if(viewList.size()>0) {
Random r = new Random();
int number = r.nextInt(viewList.size());
viewList.get(number).setVisibility(View.VISIBLE);
viewList.remove(number);
}else{
startActivity(new Intent(this,NewActivity.class));
}
}
You could create random int as follows:
//To get a Random number 1-5 (I saw your RelativeLayouts and you've 5
Random rand = new Random();
int randomNum = rand.nextInt((5 - 1) + 1) + 1;
And then you could create a method to choose what to show :
public void ShowRelativeLayout(int rand){
switch(rand){
case 1:
if (layout1.getVisibility() == View.VISIBLE) {
//Do nothing cause it's visible
break;
} else {
layout1.setVisibility(View.VISIBLE);
break;
}
case 2:
..........
}
Make an array to store the layout indexes.
RelativeLayout[] layout = new RelativeLayout[5];
layout[0] = (RelativeLayout)findViewById(R.id.layout[0]); // 0
layout[1] = (RelativeLayout)findViewById(R.id.layout[1]); // 1
layout[2] = (RelativeLayout)findViewById(R.id.layout[2]); // 2
layout[3] = (RelativeLayout)findViewById(R.id.layout[3]); // 3
layout[4] = (RelativeLayout)findViewById(R.id.layout[4]); // 4
Make a simple random number generator.
public void FindNewLayout ()
{
Random r_generator = new Random();
int randomNum;
//now the only way to know which layouts have been shown before, you
//need to store the indexes that have been used before, somewhere.
//I recommend using an array.
// count, and the array below should be initialized somewhere else
//rather than inside the method so that only one instance of each is
//created, but for simplicity I'll just put their initialization here
int static count = 0;
//I'll explain below what count does.
// the log array that remembers each layout change
boolean[] log = new boolean[5];
do
{
//select new random number
randomNum = r_generator.nextInt((max - min) + 1) + min;
//in this case max = 4, min = 0, so replace these values in the
//equation above
// check the log to see if the number has appeared again
if ( log[randomNum] == false )
{
//Great! it hasn't appeared before, so change layout
log[randomNum] = true;
layout[randomNum].setVisibility = true;
count++; // increases step
break; //stops while because an unused layout has been found
}
}while (count<5)
//if the value of count is equal to 5 then every layout has been used
//before so the do-while code should not be run again
}// end method
And the above method should be called whenever you want to try to change layout.
Finally, you can use something like the Debugger.log("message"); statement
to be printed on the console for debugging purposes if you want, in order to find out when the layout has changed.

Categories

Resources