0

I generated 1-10 random numbers and stored it in an array. My question is how I'm going to code this first, random three times if 2 or all of them are duplicates then random again three times and if they are different from each other then save to the array. so here's my code:

CODE:

int min=1;
int max=10;
int y=0;

Random rand = new Random();

for(int count=0;count<1;count++){
   int randomNum = rand.nextInt((max - min) + 1) + min;
   arr[count] = randomNum;
}
System.out.println(arr[0]);//for checking
System.out.println(randomNum);//for checking

3 Answers3

0

You can check if the array contains this random number.

Arrays.asList(arr).contains(randomNum)

If it doesn't then you add it in the array, otherwise you throw an exception or ignore in depends what your logic is.

Similar question I think: How can I test if an array contains a certain value?

Community
  • 1
  • 1
Nick
  • 156
  • 1
  • 11
0
public boolean checkArray(Int[] arr, Int targetValue) {
    for(Int i: arr){
        if(i == targetValue)
            return true;
    }
    return false;
}
dijam
  • 658
  • 1
  • 9
  • 21
0

I think this is what you're looking for :

public static int[] generatePureRandomIntegers(int n) {
    final int[] array = new int[n];
    for (int i = 0; i < n; i++) {
        array[i] = i + 1;
    }
    final Random random = ThreadLocalRandom.current();
    for (int i = array.length; i > 1; i--) {
        swap(array, i - 1, random.nextInt(i));
    }
    return array;
}

private static void swap(int[] array, int i, int j) {
    int tmp = array[i];
    array[i] = array[j];
    array[j] = tmp;
}

create a new array of ints and fill it from 1 to n then shuffle the array.

for example :

int[] randomNumbers = generatePureRandomIntegers(10);
System.out.println(Arrays.toString(randomNumbers)); // [4, 6, 5, 7, 1, 10, 8, 9, 2, 3]
FaNaJ
  • 1,329
  • 1
  • 16
  • 39