Pages

Thursday, 25 August 2016

Chapter 7 Exercise 27, Introduction to Java Programming, Tenth Edition Y. Daniel LiangY.

7.27 (Identical arrays) The arrays list1 and list2 are identical if they have the same contents. Write a method that returns true if list1 and list2 are identical, using the 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. Note that the first number in the input indicates the number of the elements in the list. This number is not part of the list.

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 1 6
Two lists are not identical



import java.util.Scanner;
 
 
 
 
public class ProgrammingEx7_27 {
 
 public static void main(String[] args) {
  Scanner input = new Scanner(System.in);
 
  System.out.print("Enter list1:");
  int[] list1 = new int[input.nextInt()];
  for (int i = 0; i < list1.length; i++) {
   list1[i] = input.nextInt();
  }
   
  System.out.print("Enter list2:");
  int[] list2 = new int[input.nextInt()];
  for (int i = 0; i < list2.length; i++) {
   list2[i] = input.nextInt();
  }
   
  if(equals(list1, list2)) {
   System.out.println("Two lists are identical");
  }else {
   System.out.println("Two lists are not identical");
  }
 
 }
  
 public static boolean equals(int[] list1, int[] list2) {
  
  
  if(list1.length != list2.length) return false;
  selectionSort(list1);
  selectionSort(list2);
   
 
  for (int i = 0; i < list2.length; i++) {
   if (list1[i] != list2[i])
    return false;
  }
 
  return true;
   
   
 }
 
  
 public static void selectionSort(int[] list) {
  for (int i = 0; i < list.length - 1; i++) {
   // Find the minimum in the list[i..list.length-1]
   int currentMin = list[i];
   int currentMinIndex = i;
 
   for (int j = i + 1; j < list.length; j++) {
    if (currentMin > list[j]) {
     currentMin = list[j];
     currentMinIndex = j;
    }
   }
 
   // Swap list[i] with list[currentMinIndex] if necessary
   if (currentMinIndex != i) {
    list[currentMinIndex] = list[i];
    list[i] = currentMin;
   }
  }
 }
}

No comments :

Post a Comment