简体   繁体   中英

How to get, return and delete a random element in an array?

How to get, return and delete a random element from an array and the most efficient to do this? The array code would look something like this:

String arr[3] = {"Cat", "Dog", "Mouse", "Horse"};

Thanks for any help.

Edit

By the way it's for a memory game, so if it repeats more than twice, I would ruin the game.

You can use % operator to create a random index in the array.Use Math.random to get a fractional random number and use it to create the random index as follows

String[] arr = {"Cat", "Dog", "Mouse", "Horse"};
    int randPos = ((int)(Math.random()*1000))%arr.length;
    String randEl = arr[randPos];
    System.out.println(randEl);

You cannot delete an element of array. All you can do is set it to null

you can do :

 String[] datas = new String[3];
 Random rand = new Random();
 rand.setSeed(System.currentTimeMillis());

 int i = rand.nextInt(datas.length);
 String val = datas[i];
 datas[i] = null;
 return val;

To get a String :

Random r = new Random();
String arr[3] = {"Cat", "Dog", "Mouse", "Horse"};
String selectedString = arr[r.nextInt(arr.length)];

For return, return the String selectedString from within a method .

To Delete

Random r = new Random();
String arr[3] = {"Cat", "Dog", "Mouse", "Horse"};
arr[r.nextInt(arr.length)] = null

Note that this won't shift the array elements, nor will the array be decreased in length.

If You need that kind of functionality, I suggest using a Collection like Arraylist

You basically cannot delete an element from an array.

Follow the following steps:

  1. Convert your array to an ArrayList

List<String> list = new ArrayList<String>(Arrays.asList(arr));

  1. Get a tandom number for index

int randPos = ((int)(Math.random()*1000))%arr.length;

  1. Delete the element at that index

list.remove(randPos);

  1. Convert it back to array of strings

arr = list.toArray(new String[0]);

Hope this helps :)

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