sdanielt
sdanielt

Reputation: 13

How to random distribute in TextView each number of an int[] once only in an android app

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!!!

Upvotes: 0

Views: 81

Answers (3)

Andrew Williamson
Andrew Williamson

Reputation: 8691

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

Upvotes: 1

deinier
deinier

Reputation: 450

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!

Upvotes: 1

boyfromvault101
boyfromvault101

Reputation: 1

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.

Upvotes: 0

Related Questions