Write a Java method public static boolean sameElements(int[] a, int[] b) that ch
ID: 3662739 • Letter: W
Question
Write a Java method
public static boolean sameElements(int[] a, int[] b)
that checks whether two arrays have the same elements in some order, with the same multiplicities.
For example the arrays,
1 4 9 16 9 7 4 9 11
and
11 1 4 9 16 9 7 4 9
would be considered identical, but the arrays
1 4 9 16 9 7 4 9 11
and
11 11 7 9 16 4 1 4 9
would not.
You will need one or more helper methods.
Your method(s) should work with the following client test code:
public static void main(String[] args) {
int[] a = {1, 4, 9, 16, 9, 7, 4, 9, 11};
int[] b = {11, 1, 4, 9, 16, 9, 7, 4, 9};
int[] c = {11, 11, 7, 9, 16, 4, 1, 4, 9};
System.out.print("The arrays a and b ");
if (!sameElements(a, b)) {
System.out.print("do not ");
}
System.out.println("have the same elements.");
System.out.print("The arrays a and c ");
if (!sameElements(a, c)) {
System.out.print("do not ");
}
System.out.println("have the same elements.");
} // end main method
Explanation / Answer
here below are the code :
/* package whatever; // don't place package name! */
import java.util.*;
import java.lang.*;
import java.io.*;
/* Name of the class has to be "Main" only if the class is public. */
class SOArrays {
public static boolean sameSet(int[] a, int[] b)
{
for (int i = 0; i < a.length; i++)
{
boolean match = false;
for (int j = 0; j < b.length; j++)
{
if (a[i] == b[j])
{
match = true;
break;
}
}
if (!match)
return false;
}
return true;
}
public static boolean equal(int[] a, int[] c)
{
for (int i = 0; i < c.length; i++)
{
boolean match = false;
for (int j = 0; j < c.length; j++)
{
if (a[i] == c[j])
{
match = true;
break;
}
}
if (!match)
return false;
}
return true;
}
public static void main(String[] args) {
int[] a = {1, 4, 9, 16, 9, 7, 4, 9, 11};
int[] b = {1, 4, 9, 16, 7, 9, 9, 10,4};
int[] c = {11, 11, 7, 9, 16, 4, 1, 4, 9};
System.out.print("The arrays a and b ");
if (sameSet(a, b)) {
System.out.print("do not ");
}
System.out.println("have the same elements.");
System.out.print("The arrays a and c ");
if (equal(a, c)) {
System.out.print("do not ");
}
System.out.println("have the same elements.");
//System.out.println("equals: "+ sameSet(a, b));
//System.out.println("equals: "+ equal(a, c));
}
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.