简体   繁体   中英

std :: random_shuffle Java analog

I'm not a C ++ specialist, so I'm asking, can anyone know if there is an analogue for std:: random_shuffle for Java? So that I also pass 2 arrays

for example std::random_shuffle ( & mask[0], &mask[81]);

For lists you can use Collections.shuffle() directly:

List<Integer> mask = new ArrayList<>();
for (int i = 0; i < 90; i++) mask.add(i);
Collections.shuffle(mask.subList(0, 81));

If you have an array of objects then you can use the following code:

Integer[] mask = new Integer[90];
for (int i = 0; i < 90; i++) mask[i] = i;
Collections.shuffle(Arrays.asList(mask).subList(0, 81));

For arrays of primitive types you would need to code it yourself.

You can use Collections.shuffle :

import java.util.ArrayList;
import java.util.Collections;


public class Main
{
    public static void main(String[] args)
    {
        ArrayList<Integer> arr = new ArrayList<>();
        for (int i = 0; i != 10; ++i) {
            arr.add(i);
        }

        Collections.shuffle(arr);

        for (int elm : arr) {
            System.out.println(elm);
        }
    }
}

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