In: Computer Science
public class contian {
/* Return true if arr2[] is contained
in arr1[] */
static boolean contains(char[] arr1,
char[] arr2, int m, int n)
{
int i = 0;
int j = 0;
for (i = 0; i < n; i++)
{
for (j = 0; j < m; j++)
if(arr2[i] == arr1[j])
break;
/* If the above inner loop
was not broken at all then
arr2[i] is not present in
arr1[] */
if (j == m)
return false;
}
/* If we reach here then all
elements of arr2[] are present
in arr1[] */
return true;
}
public static void main(String args[])
{
char[] arr1 = {'A','C' , 'P', 'I', 'K', 'S'};
char[] arr2 = {'C', 'P', 'A', 'I'};
int m = arr1.length;
int n = arr2.length;
if(contains(arr1, arr2, m, n))
System.out.print("arr2[] is "
+ "subset of arr1[] ");
else
System.out.print("arr2[] is "
+ "not a subset of arr1[]");
}
}
1. In the public static void main() we have declared 2 character arrays arr1 and arr2. We have initialized some values in these arrays.
char[] arr1 = {'A','C' , 'P', 'I', 'K', 'S'}; char[] arr2 = {'C', 'P', 'A', 'I'};
2. Then we have calculated the length of 2 arrays using length.
int m = arr1.length; int n = arr2.length;
3. Now, in the if condition we have called the contains() method passing the 2 character arays arr1 and arr2 and there corresponding sizes. If contains method returns true then if block will be executed. If contains() method returns false then else block will be executed.
if(contains(arr1, arr2, m, n)) System.out.print("arr2[] is "+ "subset of arr1[] "); else System.out.print("arr2[] is "+ "not a subset of arr1[]");
4. Now come to the contains() method. It has a return type of boolean because it will return either true or false. contain() method has 2 parameters which are the 2 character arrays.
static boolean contains(char[] arr1,char[] arr2, int m, int n)
5. Then we have made 2 integer type variables i and j which are initialized to 0.
int i = 0; int j = 0;
6. Then we have started a loop to iterate second character array arr2. In the second loop inside the first loop we are iterating the first character array arr1.
for (i = 0; i < n; i++) { for (j = 0; j < m; j++)
7. Then we have used a if condition to check if the current value of first array is equal to the current value of second array or not. If they are equal then we break out of second loop because we now want the next character of first array with the current character of second array.
if(arr2[i] == arr1[j]) break;
8. If the above for loop does not break then that means arr2 is not present in arr1 bacause we searched the complete arr1 for a character of arr2 which was not found equal to any of the characters present in arr1. So, j becomes equal to m and we return false.
if (j == m) return false;
9. If each of the characters of arr2 were present in arr1 then we will never execute the above if condition where j==m. And we will successfully come out of the first loop and return true.
return true;
Output