Question

In class we wrote a method closestPairFast that on an input array of numbers, finds the...

In class we wrote a method closestPairFast that on an input array of numbers, finds the distance of the closest pair by first sorting the input array and then finding the closest adjacent pair. (See the file ClosestPair1D.java in the Code folder on D2L.) In this problem, you are asked to modify the method so that it returns an integer array consisting of the indices of the closest pair in the original array. If there is a tie, just return the indices of an arbitrary closest pair. The skeleton for the new method, closestPairFast2, is provided in the file Hw1_p2.java in the Homework Files folder.

The following is a sample run:

Input:   8 15 19 3 12

Return value:   1 4

Explanation: The closest pair is (15, 12). The indices of 15 and 12 in the original array are 1 and 4 respectively.

The method closestPairFast2 should have the same structure as closestPairFast and have time complexity ?(?????), where ? is the length of the input array.

Hint: Define a helper class consisting of two attributes: (1) the value of an element and (2) its index in the original input array. Have the class implement the Comparable interface so that you can sort by value and keep the original indices.

public class Hw1_p2_updated {
   // HW1 Problem 2
   public static int[] closestPairFast2(long[] A) {
       int[] ans = new int[2];
       int n = A.length;
       ValIndexPair[] B = new ValIndexPair[n];
       for (int i = 0; i < n; i++) {
           B[i] = new ValIndexPair(A[i], i);
       }
      
       Arrays.sort(B);
      
       // Your code starts
      
      
       // Your code ends
      
       return ans;
   }
  
   public static void main(String[] args) {
       // Test driver for closestPairFast2
       int n = 5;
       long[] A = new long[n];
       for (int i = 0; i < n; i++) {
           A[i] = (long) (Math.random() * 100);
           System.out.print(A[i] + " ");
       }
       System.out.println("\n");
       closestPairFast2(A);
      
   }
}

class ValIndexPair implements Comparable<ValIndexPair> {
   long val;
   int idx;
  
   ValIndexPair(long val, int idx) {
       this.val = val; this.idx = idx;
   }
  
   public int compareTo(ValIndexPair o) {
       if (this.val < o.val) return -1;
       else if (this.val == o.val) return 0;
       else return 1; // this.val > o.val
   }
}

0 0
Add a comment Improve this question Transcribed image text
Answer #1

import java.util.*;
public class Main {
// HW1 Problem 2
public static int[] closestPairFast2(long[] A) {
int[] ans = new int[2];
int n = A.length;
ValIndexPair[] B = new ValIndexPair[n];
for (int i = 0; i < n; i++) {
B[i] = new ValIndexPair(A[i], i);
}
  
Arrays.sort(B);
// System.out.println(Arrays.toString(B));
// Your code starts
long min=B[1].val-B[0].val;
// int min_index=1;
for(int i=0;i<n-1;i++){
if(min>B[i+1].val-B[i].val){
min=B[i+1].val-B[i].val;
// min_index=i+1;
ans[0]=B[i].idx;
ans[1]=B[i+1].idx;
}
}
  
// Your code ends
return ans;
}
  
public static void main(String[] args) {
// Test driver for closestPairFast2
int n = 5;
long[] A = new long[n];
for (int i = 0; i < n; i++) {
A[i] = (long) (Math.random() * 100);
System.out.print(A[i] + " ");
}
System.out.println("\n");
int[] temp=closestPairFast2(A);
System.out.println(temp[0]+" "+temp[1]);
}
}

class ValIndexPair implements Comparable<ValIndexPair> {
long val;
int idx;
  
ValIndexPair(long val, int idx) {
this.val = val; this.idx = idx;
}
  
public int compareTo(ValIndexPair o) {
if (this.val < o.val) return -1;
else if (this.val == o.val) return 0;
else return 1; // this.val > o.val
}
}

Add a comment
Know the answer?
Add Answer to:
In class we wrote a method closestPairFast that on an input array of numbers, finds the...
Your Answer:

Post as a guest

Your Name:

What's your source?

Earn Coins

Coins can be redeemed for fabulous gifts.

Not the answer you're looking for? Ask your own homework help question. Our experts will answer your question WITHIN MINUTES for Free.
Similar Homework Help Questions
  • Array with Iterator. Java style Implement an array data structure as a class JstyArray<E> to support...

    Array with Iterator. Java style Implement an array data structure as a class JstyArray<E> to support the Iterable interface such that the following code works: JstyArray<Integer> data; data = new JstyArray<Integer>(10); for (int i = 0; i < 10; ++i) { data.set(i, new Integer(i) ); } int sum = 0; for ( int v : data ) { if (v == null) continue; // empty cell sum += v; } The iterator provided by this class follows the behaviour of...

  • PrintArray vi Create a class called PrintArray. This is the class that contains the main method....

    PrintArray vi Create a class called PrintArray. This is the class that contains the main method. Your program must print each of the elements of the array of ints called aa on a separate line (see examples). The method getArray (included in the starter code) reads integers from input and returns them in an array of ints. Use the following starter code: //for this program Arrays.toString(array) is forbidden import java.util.Scanner; public class PrintArray { static Scanner in = new Scanner(System.in);...

  • You will implement the following method public static int[] linearSearchExtended(int[][] numbers, int key) { // Implement...

    You will implement the following method public static int[] linearSearchExtended(int[][] numbers, int key) { // Implement this method return new int[] {}; }    There is a utility method provided for you with the following signature. You may use this method to convert a list of integers into an array. public static int[] convertIntegers(List<Integer> integers) Provided code import java.util.ArrayList; import java.util.Iterator; import java.util.List; import java.util.Scanner; public class MatrixSearch { // This method converts a list of integers to an array...

  • The code snippet below is an example of pass by reference. We also provide a sample...

    The code snippet below is an example of pass by reference. We also provide a sample method setZeroAt, which sets 0 at a position i in the array, to illustrate pass by reference. public class Sample { public static void setZeroAt(int [] arr, int i){ arr[i] = 0; } public static void main(String[] args) { Scanner input = new Scanner(System.in); int sample[] = {1, 2, 3}; setZeroAt(sample, 1); //Now sample looks like {1, 0, 3} } } Write a Java...

  • Which of the following are valid array declarations? a. int[] array- new int[10]; b. double [array...

    Which of the following are valid array declarations? a. int[] array- new int[10]; b. double [array double[10]; c. charl charArray "Computer Science"; None of the above Analyze the following code: class Test public static void main(Stringl] args) System.out.println(xMethod(10); public static int xMethod(int n) System.out.println("int"); return n; public static long xMethod(long n) System.out.,println("long"); return n The program displays int followed by 10 The program displays long followed by 10. The program does not compile. None of the above. tions 3-4 are...

  • 1. What is the output? System.out.print(3 + 3 * 3); a. 18 b. 12 c. 9 d. 0 e. 10             2.   What is output by the code below? System.out.print("\\dog\\cat&#...

    1. What is the output? System.out.print(3 + 3 * 3); a. 18 b. 12 c. 9 d. 0 e. 10             2.   What is output by the code below? System.out.print("\\dog\\cat"); a. dog b. dogcat c. \\dog\\cat d. \dog\cat e. catdog\\\\             3.   What is returned by the call     getIt(9) ? public static int getIt(int num){ int ans = 0; if( num >=2 ) {      if( num >= 7)         ans += 2;      else         ans += 3; } ans += 4; return ans; }...

  • Can someone help me with the main class of my code. Here is the assignment notes....

    Can someone help me with the main class of my code. Here is the assignment notes. Implement project assignment �1� at the end of chapter 18 on page 545 in the textbook. Use the definition shown below for the "jumpSearch" method of the SkipSearch class. Notice that the method is delcared static. Therefore, you do not need to create a new instance of the object before the method is called. Simply use "SkipSearch.jumpSearch(...)" with the appropriate 4 parameter values. When...

  • Java Array The method rotateLeft() takes in a reference a to an integer array and a...

    Java Array The method rotateLeft() takes in a reference a to an integer array and a positive integer n and it returns a new array whose contents is the contents of the input array rotated to the left n places. So each element a[i] of the input array should be placed at location b[i-n] of the returned array. If the index i-n is negative, then that index should "wrap" around to the end of the output array. For example, if...

  • need help editing or rewriting java code, I have this program running that creates random numbers...

    need help editing or rewriting java code, I have this program running that creates random numbers and finds min, max, median ect. from a group of numbers,array. I need to use a data class and a constructor to run the code instead of how I have it written right now. this is an example of what i'm being asked for. This is my code: import java.util.Random; import java.util.Scanner; public class RandomArray { // method to find the minimum number in...

  • JAVA Code: Complete the method, sumOdds(), below. The method takes in an array of integers, numbers,...

    JAVA Code: Complete the method, sumOdds(), below. The method takes in an array of integers, numbers, and returns the sum of all the odd numbers in the array. The method should return 0 if the array contains no odd numbers. For example, if the given array is [12, 10, 5, 8, 13, 9] then the method should return 27 (5+13+9=27). Starter Code: public class Odds { public static int sumOdds(int[] numbers) { //TODO: complete this method    } }

ADVERTISEMENT
Free Homework Help App
Download From Google Play
Scan Your Homework
to Get Instant Free Answers
Need Online Homework Help?
Ask a Question
Get Answers For Free
Most questions answered within 3 hours.
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT