javaarraysrandomnon-repetitive

Generation of 4 non repeating random numbers using arrays in java


I have this array

int [] marc = new int[4];

i need to insert a set of non repeating random numbers in the range of 1-10 to it

i'm using this for loop to set random numbers

for (he = 0; he < 4; he++) {
    marc[he] = rn.nextInt(10 - 1 + 1) + 1;
    marc[he]++; 
}

it gives me random numbers but repeated ones inside the array

i'm also using

java.util.Random;

Solution

  • Well, yes, numbers can be repeated while being random. You need to do your own logic to validate if they're already on the array, this can be done with the following code:

    In the code I used an array of 10 elements to observe there aren't repeated numbers even on that situation.

    import java.util.Random;
    
    public class RandomNumbersNoRepeating {
        public static void main(String[] args) {
            int array[] = new int[10];
            Random random = new Random();
    
            //Fills the array
            for (int i = 0; i < array.length; i++) {
                boolean found = false;
                int r = 0;
                do {
                    found = false;
                    r = random.nextInt(10) + 1;
                    //Here we check if the number is not on the array yet
                    for (int j = 0; j < array.length; j++) {
                        if (array[j] == r) {
                            found = true;
                            break;
                        }
                    }
                } while (found);
    
                array[i] = r;
            }
    
            //Prints the array
            for (int i = 0; i < array.length; i++) {
                System.out.println(array[i]);
            }
        }
    }
    

    Another possible solution, as given in a comment could be to shuffle an array from 1-10, and get the first four numbers