Question

In: Computer Science

Please follow the instructions carefully and complete the code given below. Language: Java Instructions from your...

Please follow the instructions carefully and complete the code given below.

Language: Java

Instructions from your teacher:

(This is a version of an interview question I once saw.) In this problem, we will write a program that, given an integer k, an integer n, and a list of integers, outputs the number of pairs in in the list that add to k.

To receive full credit for design, your algorithm must have a runtime in O(n) , where n is the length of the list of integers. Hint: you can assume that the contains in a HashSet is O(1). Your program should take as input a number k on its own line, followed by a number n on its own line, followed by a space-separated list of n integers. It should then output the number of pairs in the list that add to k. Order does not matter when considering a pair (in other words, in the list [2,1] there is one distinct pair that sums to 3, not two). You may assume that all numbers in the input are distinct. For example, if our file input.txt is:

1

6

1 2 3 4 -2 -3

then we should print 2 since there are two pairs that sum to 1: 3 + (-2) and 4 + (-3).

As another example, if input.txt is:

3

4

1 2 3 4

then we should print 1since there is one pair that sums to 1: 1+2.

The problem PairFinder provides starter code for reading and printing; your task is to fill in thefindPairs()method.

.......................................................................................................................

import java.util.Scanner;

public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
  
// Read in the value of k
int k = Integer.parseInt(sc.nextLine());
  
// Read in the value of n
int n = Integer.parseInt(sc.nextLine());
  
// Read in the list of numbers
int[] numbers = new int[n];
String input = sc.nextLine();
if (input.equals("")) {
numbers = new int[0];
} else {
String[] numberStrings = input.split(" ");
for (int i = 0; i < n; i++) {
numbers[i] = Integer.parseInt(numberStrings[i]);
}
}
  
System.out.println(findPairs(numbers, k));
}
  
private static int findPairs(int[] numbers, int k) {
// TODO fill in this function
throw new UnsupportedOperationException();
}
  
}

Solutions

Expert Solution

Thanks for the question.

Below is the code you will be needing  Let me know if you have any doubts or if you need anything to change.

Thank You !!

===========================================================================

import java.util.Arrays;
import java.util.Scanner;

public class Main {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);

// Read in the value of k
        int k = Integer.parseInt(sc.nextLine());

// Read in the value of n
        int n = Integer.parseInt(sc.nextLine());

// Read in the list of numbers
        int[] numbers = new int[n];
        String input = sc.nextLine();
        if (input.equals("")) {
            numbers = new int[0];
        } else {
            String[] numberStrings = input.split(" ");
            for (int i = 0; i < n; i++) {
                numbers[i] = Integer.parseInt(numberStrings[i]);
            }
        }

        System.out.println("Pairs found: "+findPairs(numbers, k));
    }

    private static int findPairs(int[] numbers, int k) {

        Arrays.sort(numbers);
        int start = 0;
        int end = numbers.length - 1;
        int count = 0;
        while (start <= end) {

            int total = numbers[start] + numbers[end];
            if (total == k) {
                count++;
                start++;
                end--;
            } else if (total > k) end--;
            else start++;

        }
        return count;

    }

}

============================================================


Related Solutions

Please carefully review the code to fill in after the given instructions and complete the code...
Please carefully review the code to fill in after the given instructions and complete the code for me. Thank you in advance. In this problem, we will implement a simple dictionary of common words in the English language, represented as an array of words paired with their lengths. You will need to implement each of the below methods in the Dictionary class. In this problem, the first line of input represents the method to call. It will be one of...
Please Read Carefully Before start answering this question. Please follow the instructions. This Question is from...
Please Read Carefully Before start answering this question. Please follow the instructions. This Question is from 'BSBFIM501 Manage budgets and financial plans' course. There are no parts missing for this Question; guaranteed!. This is the original Screenshot direct from the question. Therefore, there are nothing any further information can be provided. Thanks for your understanding and Cooperation. Please answer the following questions from the topics discussed for Prepare, implement, monitor and modify contingency plans: 1.a. Explain the process of preparing...
Please complete the following code in C using the comments as instructions. Further instructions are below...
Please complete the following code in C using the comments as instructions. Further instructions are below the code. challenge.c // goal: print the environment variables to the file "env.txt", one per line // (If envp is NULL, the file should be empty, opening in write mode will do that.) // example: // inputs: // envp/environ = {"E1=2","E2=7",NULL} // outputs: // env.txt as a string would be "E1=2\nE2=7\n" // example: // inputs: // envp/environ = {NULL} or NULL // outputs: //...
As code is given below, follow the instructions: 1. Count the number of comparisons and find...
As code is given below, follow the instructions: 1. Count the number of comparisons and find where to put that counter in the code 2. Pick a random pivot, right pivot, left pivot, middle pivot for each smaller array /sub-array import java.util.*; import java.util.List; public class QuickSort { public static void main(String[] args) { int[] values = { 6, 5, 4, 3, 1, 7, 8 }; System.out.println("Original order: "); for (int element : values) System.out.print(element + " "); IntQuickSorter.quickSort(values); System.out.println("\nFirst...
Complete ArrayCollection.java with following methods (Please complete code in java language): public ArrayCollection(); public ArrayCollection(int size);...
Complete ArrayCollection.java with following methods (Please complete code in java language): public ArrayCollection(); public ArrayCollection(int size); public boolean isEmpty(); public boolean isFull(); public int size(); // Return number of elements in the Collection. public String toString(); public boolean add(T element); // Add an element into the Collection, return true if successful public boolean remove(T target); // Remove the target from Collection, return true if successful public boolean removeAll(T target); // Remove all occurrences of Target, return if successful public void...
Language for this question is Java write the code for the given assignment Given an n...
Language for this question is Java write the code for the given assignment Given an n x n matrix, where every row and column is sorted in non-decreasing order. Print all elements of matrix in sorted order.Input: The first line of input contains an integer T denoting the number of test cases. Then T test cases follow. Each test case contains an integer n denoting the size of the matrix. Then the next line contains the n x n elements...
Write the basic JAVA code for the beginners and follow all the instructions listed 1. A...
Write the basic JAVA code for the beginners and follow all the instructions listed 1. A year with 366 days is called a leap year. A year is a leap year if it is divisible by 4 (for e.g., 1980), except that it is not a leap year if it is also divisible by 100 (for e.g., 1900); however, it is a leap year if it is further divisible by 400 (for e.g., 2000). Write a program that prompts the...
Project Instructions Please read the following instructions and review the table below carefully. Then, enter answers...
Project Instructions Please read the following instructions and review the table below carefully. Then, enter answers for journal items [A] to [V] in the next item in this lesson, called Project 1 Part 1 Journal Entries for Accrual Accounting. You may keep these instructions open in a separate browser or download the instructions as a PDF, and open it as you work through the exercise. Illini Company, Inc. Balance Sheet as of 12/31/20X0 Assets Current Assets: Cash 1,500,000 Accounts receivable,...
Consider the scenario below, then follow the instructions underneath it to complete the discussion. If appropriate,...
Consider the scenario below, then follow the instructions underneath it to complete the discussion. If appropriate, support your position with credible resources/examples/evidence and provide APA references. Mr. B Mr. B, a 70-year-old male client, presented to his primary care physician with complaints of blurred vision and headaches over the last two months. On several visits, Mr. B's blood pressure was found to be elevated, so the physician started him on hydrochlorothiazide 25 mg by mouth daily. One month later, Mr....
Consider the scenario below, then follow the instructions underneath it to complete the discussion. If appropriate,...
Consider the scenario below, then follow the instructions underneath it to complete the discussion. If appropriate, support your position with credible resources/examples/evidence and provide APA references. Mr. B Mr. B, a 70-year-old male client, presented to his primary care physician with complaints of blurred vision and headaches over the last two months. On several visits, Mr. B's blood pressure was found to be elevated, so the physician started him on hydrochlorothiazide 25 mg by mouth daily. One month later, Mr....
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT