Untitled

fill array no dup
mail@pastecode.io avatar
unknown
java
2 years ago
1.6 kB
5
Indexable
Never
import java.util.Arrays;
import java.util.Random;

public class Main {
    public static void main(String[] args) {
        int[] myArray = new int[6];

        fillArray(myArray);

        System.out.println(Arrays.toString(myArray));

    }

    // one major flaw of this is when you generate a low range of number.
    // e.g. 1-5 (because getting a duplicate from 1-5 is very high,
    // so it won't continue unless it doesn't get a duplicate.)
    static int[] fillArray(int[] arr) {

        for (int i = 0; i < arr.length; i++) {
            int randomNumber = generateNumber(1, 10);

            // only check if we are on the second iteration
            // meaning arr has at least one value now.
            if (i > 1) {
                // if the generated number (randomNumber) already exist in the array;
                // we decrement i so that we don't fill that index in the array with the duplicate value
                if (isDuplicate(arr, randomNumber)) {
                    i--;
                    continue;
                }
            }
            arr[i] = randomNumber;
        }

        return arr;
    }

    // helper functions
    static int generateNumber(int minRandomVal, int maxRandomVal) {
        return new Random().nextInt(minRandomVal, maxRandomVal + 1);
    }

    static boolean isDuplicate(int[] arr, int toCheck) {
        boolean isFound = false;
        for (var number : arr) {
            if (number == toCheck) {
                isFound = true;
                break;
            }
        }
        return isFound;
    }
}