Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

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));
}
}

Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
Chat Now And Get Quote