0

I am making an Array that is 10 integers long, so that each place 0-9 contains a different integer 0-9.

I am having trouble figuring out how to check if the array already contains a certain number, and if so, regenerating a new one.

So far I have:

for (int i = 0; i < perm.length; i++)
{
    int num = (int) (Math.random() * 9); 
    int []

    perm[i] = num;   
}
Paul Roub
  • 36,322
  • 27
  • 84
  • 93
user1729448
  • 149
  • 1
  • 4
  • 12

3 Answers3

3
Arrays.asList(perm).contains(num) 

from How can I test if an array contains a certain value?

for (int i = 0; i < perm.length; i++)

this is not enough to loop like this, if collision happens some slots would have been not initalized.

Overall, for this task you better initialize array with values in order and then shuffle it by using random permutation indexes

Community
  • 1
  • 1
Nikolay Kuznetsov
  • 9,467
  • 12
  • 55
  • 101
0

here is a complete answer

int[] array = {3,9, 6, 5, 5, 5, 9, 10, 6, 9,9};

    SortedSet<Integer> s = new TreeSet();
    int numberToCheck=61;
    for (int i = 0; i < array.length; i++) {
        s.add(array[i]);
    }

    System.out.println("Number contains:"+!(s.add(numberToCheck)));


    System.out.println("Sorted list:");
    System.out.print(s);
Samitha Chathuranga
  • 1,689
  • 5
  • 30
  • 57
0

Adding both string and integer to check is exist or not.

public class existOrNotInArray {

public static void elementExistOrNot() {
    // To Check Character exist or not
    String array[] = { "AB", "CD", "EF" };

    ArrayList arrayList = new ArrayList<>();

    String stringToCheck = "AB";

    for (int i = 0; i < array.length; i++) {
        arrayList.add(array[i]);
    }

    System.out.println("Character exist : " + arrayList.contains(stringToCheck));

    // To Check number exit or not
    int arrayNum[] = { 1, 2, 3, 4 }; // integer array

    int numberToCheck = 5;

    for (int i = 0; i < arrayNum.length; i++) {
        arrayList.add(arrayNum[i]);
    }
    System.out.println("Number exist :" + arrayList.contains(numberToCheck));
}

public static void main(String[] args) {
    elementExistOrNot();
}
}
Mjachowdhury
  • 85
  • 10