Reputation: 149
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;
}
Upvotes: 0
Views: 50844
Reputation: 81
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();
}
}
Upvotes: 0
Reputation: 1749
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);
Upvotes: 0
Reputation: 9579
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
Upvotes: 4