Sandeep Johal
Sandeep Johal

Reputation: 429

How to check ensure a array does not contain the same element twice

I have a loop which assigns randomly generated integers into an array. I need a way to ensure the same integer is not input into the array twice.

I figured creating a loop inside the overall loop would work but I am unsure on what to execute here.

int wwe[] = new int[9];
for(int i = 0; i < 9 ; i++){
    int randomIndex = generator.nextInt(wwe.length);
    wwe[i] = randomIndex;

    System.out.println(wwe[i]);
    System.out.println("########");
    for(int j = 0; j < 9; j++){
        System.out.println("This is the inner element " + wwe[j]);
    }
}

Upvotes: 1

Views: 1002

Answers (4)

Kiran Mohan
Kiran Mohan

Reputation: 3016

Something similar to the following should meet your requirement.
It uses a HashSet to achieve unique elements.

    Set<Integer> sint = new HashSet<>();
    Random random = new Random();

    while ( sint.size() < 9){
        sint.add(random.nextInt());
    }

Upvotes: 1

amit
amit

Reputation: 178521

You are actually looking for shuffling your array.

Note that what you really looking for is to find a random order of your array, this is called a permutation.

In java, it can be simply done using a list with Collections.shuffle().
If you are looking to implement it on your own - use fisher yates shuffle, it is fairly easy to implement.

Since other answers showed how to do it with Collections.shuffle() already - here is a simple implementation + example of fisher yates shuffle, that does not need to convert the original array into a list.

private static void swap (int[] arr, int i1, int i2) {
    int temp = arr[i1];
    arr[i1] = arr[i2];
    arr[i2] = temp;
}
private static void shuffle(int[] arr, Random r) { 
    for (int i =0; i < arr.length; i++) {
        int x = r.nextInt(arr.length - i) + i;
        swap(arr,i,x);
    }
}
public static void main(String... args) throws Exception {
    int[] arr = new int[] {1 , 5, 6, 3, 0, 11,2,9 };
    shuffle(arr, new Random());
    System.out.println(Arrays.toString(arr));
}

Upvotes: 1

jackalope
jackalope

Reputation: 1564

For you example, you can use Collections.shuffle

public static void main(String[] args) {
    List<Integer> a = new ArrayList<>(9);
    for (int i = 0; i < 9; i++) {
      a.add(i);
    }
    Collections.shuffle(a);
    System.out.println(a);
  }

Upvotes: 0

Karthik T
Karthik T

Reputation: 31972

If you want to enforce unique values, use a data structure meant for such a behavior, like a Set. TreeSet or HashSet would work perfectly.

Upvotes: 4

Related Questions