简体   繁体   中英

Sorting int variables in ascending order

I am creating a lottery number generator in android, but have come to a recent standstill.

The way it works is, I populate an array list by looping through various times. Then I shuffle the array list by calling collections.shuffle. And finally, I create five int variables to obtain the first 5 elements from the array list. This is all fine.

Now my problem is trying to print these out in ascending order. I have come across collections.sort, unfortunately this does not help, as it will only sort the array list in ascending order, removing my original aim of a unique random order.

Is there a way to get the following 5 integer variables to print in ascending order?

I couldn't find any relevent documentation on allowing me to add these 5 int variables to an int array and then call sort on the array, if that's at all possible.

 public void onClick(View view) {
    ArrayList<Integer> euroList = new ArrayList<Integer>();
    TextView textView1 = (TextView) findViewById(R.id.textview2);

    for (int i = 1; i <= 50; i++) {
        euroList.add(i);
    }

    Collections.shuffle(euroList);

    textView1.setText("");

    int num1 = euroList.get(0);
    int num2 = euroList.get(1);
    int num3 = euroList.get(2);
    int num4 = euroList.get(3);
    int num5 = euroList.get(4);



    textView1.setText(String.valueOf(num1) + " " + String.valueOf(num2)
            + " " + String.valueOf(num3) + " " + String.valueOf(num4) + " "
            + String.valueOf(num5));

Thank you for your time.

You can sort the first 5 elements of the list before extracting them. After the shuffle, and before getting the resulting elements, add this:

Collections.sort(euroList.subList(0, 5));

The whole thing will then look like this:

Collections.shuffle(euroList);
Collections.sort(euroList.subList(0, 5));

int num1 = euroList.get(0);
int num2 = euroList.get(1);
int num3 = euroList.get(2);
int num4 = euroList.get(3);
int num5 = euroList.get(4);

Extract the five int values to a new ArrayList <Integer> first. Sort that list. Then determine num1, num2,n...

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM