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

Java programming assignment: Write code for a method public static boolean sameE

ID: 667462 • Letter: J

Question

Java programming assignment:

Write code for a method

public static boolean sameElemens(int[] a, int[] b)

that checks whether two arrays have the same elements in some order, with the same multiplicities. For example, two arrays

121    144    19    161    19    144    19    11

and

11    121    144    19    161    19    144    19

would be considered to have the same elements because 19 appears three times in each array, 144 appears twice in each array, and all other elements ppear once in each array.

Use the following code to test solution.

import java.util.Array

public class Application{

// Insert solution to programming exercise here (use to test solution).

    public static void main(String[] args) {
        int[] a = {121, 144, 19, 161, 19, 144, 19, 11};
        int[] b = {11, 121, 144, 19, 161, 19, 144, 19};
        if (sameElements(a, b)) {
            System.out.println("Test 1 passed");
        } else {
            System.out.println("Test 1 failed");
        }
        int[] c = {11, 121, 144, 18, 161, 19, 144, 19};
        if (sameElements(a, c)) {
            System.out.println("Test 2 failed");
        } else {
            System.out.println("Test 2 passed");
        }

    }
}

Explanation / Answer

working code

public static boolean sameElements(int[] a, int[] b)
   {
      Arrays.sort(a);
        Arrays.sort(b);
        if (Arrays.equals(a, b))
             return true;
        else
           return false;
   }
   public static void main (String[] args) throws java.lang.Exception
   {
       int[] a = {121, 144, 19, 161, 19, 144, 19, 11};
        int[] b = {11, 121, 144, 19, 161, 19, 144, 19};
        if (sameElements(a, b)) {
            System.out.println("Test 1 passed");
        } else {
            System.out.println("Test 1 failed");
        }
        int[] c = {11, 121, 144, 18, 161, 19, 144, 19};
        if (sameElements(a, c)) {
            System.out.println("Test 2 failed");
        } else {
            System.out.println("Test 2 passed");
        }
   }

tested on ideone

http://ideone.com/tJLRZX

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