0

I have 4 numbers as follows :

int[] myresult = {result1, result2, result3, result4};

I need to bring up each of the 4 numbers only once in each of the 4 textviews I created. Here is the code I wrote, but there are duplicates :

    int r1 = (int)(Math.random()*4);
    int r2 = (int)(Math.random()*4);
    int r3 = (int) (Math.random()*4);
    int r4 = (int) (Math.random()*4);

    final int answer1 = myresult[r1];
    final int answer2 = myresult[r2];
    final int answer3 = myresult[r3];
    final int answer4 = myresult[r4];

    tvanswer1.setText(Integer.toString(answer1));
    tvanswer2.setText(Integer.toString(answer2));
    tvanswer3.setText(Integer.toString(answer3));
    tvanswer4.setText(Integer.toString(answer4));

Please help me to find the solution!

Thank you!!!

1
  • I think this may be what you need Commented Feb 3, 2016 at 20:49

3 Answers 3

1

Have a look at Collections.shuffle(). Basically, all you need to do is create a list with all the possible values, then shuffle it.

List<Integer> values = new ArrayList<Integer>();
for (int i = 0; i < myresult.length; i++)
    values.add(myresult[i]);

Collections.shuffle(values);

tvanswer1.setText(values.get(0).toString());
tvanswer2.setText(values.get(1).toString());
...
Sign up to request clarification or add additional context in comments.

Comments

1

You can swap N times two elements in the initial array.

//For N = 20:

Random random = new Random();

for(int i=0;i<20;i++)
{
    int pos1 = random.nextInt() % 4;

    int pos2 = random.nextInt() % 4;

    int temp = myresult[pos1];

    myresult[pos1] = myresult[pos2];

    myresult[pos2] = temp;
}

Then:

tvanswer1.setText(Integer.toString(myresult[0]));

tvanswer2.setText(Integer.toString(myresult[1]));

tvanswer3.setText(Integer.toString(myresult[2]));

tvanswer4.setText(Integer.toString(myresult[3]));

Hope this helps!

Comments

0

You need to keep track of what you have already selected. One way would be if your first number is 3, and your next random number is also 3 then go to the next un-selected number. This can be done by with another array of booleans that you just scan and set to true or false depending if they have been used yet.

I am not sure what you are using this for, I would use an ArrayList and just remove the numbers once they have been selected. Then you would just get a new random number within the size of the ArrayList.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.