Problem 1 (Identical array) The arrays list1 and list2 are identical if they hav
ID: 3668833 • Letter: P
Question
Problem 1
(Identical array) The arrays list1 and list2 are identical if they have the same size and content only (same content with different order still consider as identical). Write a method that returns true if list1 and list2 are identical, using following header:
public static boolean equals(int[] list1, int[] list2)
Write a test program that prompts the user to enter two lists of integers and displays whether the two are identical. Here are the sample runs.
Here are sample runs of the program:
Enter list1: 5 2 -5 6 6 1
Enter list2: 5 -5 2 6 1 6
Two lists are identical
Enter list1: 5 5 5 6 6 1
Enter list2: 5 2 5 6 6 1
Two lists are not identical
Enter list1: 5 -5 5 6 6 1
Enter list2: 5 2 5 6 6 1
Two lists are not identical
Explanation / Answer
Here is the code for you:
class ItendicalLists
{
public static int[] selectionSort(int[] arr){
for (int i = 0; i < arr.length - 1; i++)
{
int index = i;
for (int j = i + 1; j < arr.length; j++)
if (arr[j] < arr[index])
index = j;
int smallerNumber = arr[index];
arr[index] = arr[i];
arr[i] = smallerNumber;
}
return arr;
}
public static boolean equals(int[] list1, int[] list2)
{
list1 = selectionSort(list1);
list2 = selectionSort(list2);
if(list1.length != list2.length)
return false;
for(int i = 0; i < list1.length; i++)
if(list1[i] != list2[i])
return false;
return true;
}
public static void main(String[] args)
{
int[] list1 = {5, 2, -5, 6, 6, 1};
int[] list2 = {5, -5, 2, 6, 1, 6};
equals(list1, list2);
if(equals(list1, list2))
System.out.println("Two lists are identical.");
else
System.out.println("Two lists are not identical.");
}
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.