In: Computer Science
2 Write a function named equivalentArrays that has two array arguments and returns 1 if the two arrays contain the same values (but not necessarily in the same order), otherwise it returns 0. Your solution must not sort either array or a copy of either array! Also you must not modify either array, i.e., the values in the arrays upon return from the function must be the same as when the function was called. Note that the arrays do not have to have the same number of elements, they just have to have one of more copies of the same values.
If you are programming in Java or C#, the function prototype is int equivalentArrays(int[ ] a1, int[ ] a2)
If you are programing in C or C++, the function prototype is int equivalentArrays(int a1[ ], int a2[ ], int len1, int len2) where len1 is the number of elements in a1 and len2 is the number of elements in a2.
Hint: If your solution compares the length of the first array with the length of the second array or vice versa, you have misunderstood the problem!! Your solution does not need to determine which array is bigger!
public class EquivalentArrays { public static int equivalentArrays(int[] a1, int[] a2) { for (int i = 0; i < a1.length; i++) { boolean found = false; for (int j = 0; j < a2.length; j++) { if (a1[i] == a2[j]) { found = true; } } if (!found) { return 0; } } for (int i = 0; i < a2.length; i++) { boolean found = false; for (int j = 0; j < a1.length; j++) { if (a2[i] == a1[j]) { found = true; } } if (!found) { return 0; } } return 1; } public static void main(String[] args) { int[] a1 = {3, 2, 1, 8, 5}; int[] a2 = {1, 5, 2, 3, 8}; int[] a3 = {1, 5, 2, 3, 8, 9}; System.out.println(equivalentArrays(a1, a2)); System.out.println(equivalentArrays(a1, a3)); } }