Randomly remove elements from array

Joined
Jun 14, 2021
Messages
6
Reaction score
0
I would like to learn how to randomly remove the elements from an array in Java, one at a time. The below program is what I have written:

Java:
//randomly remove elements from an array

import java.util.Random;

public class Main {

public static void main(String[] args) {
    int size = 5;

    Random r = new Random();
    int result = r.nextInt(size);

    String[] arr1 = {"1", "2", "3", "4", "5", "6"};

        for (int i = 0; i < size; i++) {
               arr1[i] = arr1[size];
            }
            System.out.println(arr1);
        }   
    }

I am looking for help with printing the result to check that it is empty (might need toString) and also the logic for removing the elements.
 
Joined
Jul 4, 2023
Messages
507
Reaction score
63
Try use: Arrays.toString(Arrays.copyOfRange(arr1, 0, size)))

[ Working code on-line ]
Java:
import java.util.Random;
import java.util.Arrays;

public class Main {

    public static void main(String[] args) {
        // Define initial array
        String[] arr1 = {"a", "b", "c", "d", "e", "f"};
        int size = arr1.length; // Current size of the array
        
        // Create an instance of Random
        Random r = new Random();

        // Pick a random index to remove
        int indexToRemove = r.nextInt(size);
        System.out.println("Element to remove: " + arr1[indexToRemove]);

        // Print the array before removing the element
        System.out.println("Before removal: " + Arrays.toString(Arrays.copyOfRange(arr1, 0, size)));

        // Remove the element at the random index by shifting elements
        for (int i = indexToRemove; i < size - 1; i++) {
            arr1[i] = arr1[i + 1]; // Shift elements to the left
        }
            
        // Reduce the size of the array
        size--;

        // Print the array after removing the element
        System.out.println(" After removal: " + Arrays.toString(Arrays.copyOfRange(arr1, 0, size)));
    }

}
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
474,053
Messages
2,570,431
Members
47,075
Latest member
TysonV438

Latest Threads

Top