Created
January 16, 2021 20:48
-
-
Save aryan-dixit-26/d963df78ac71623810879533fd51595d to your computer and use it in GitHub Desktop.
Answer - QUESTION1 : Pairs
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| import java.util.*; | |
| class Pair { | |
| int x; | |
| int y; | |
| @Override | |
| public String toString() { | |
| return "{" + | |
| "x=" + x + | |
| ", y=" + y + | |
| '}'; | |
| } | |
| } | |
| class Question1 { | |
| // Please try not to change anything in this method. | |
| public static void main(String[] args) { | |
| int[] numbers = new int[15]; | |
| addRandomNumbers(numbers); | |
| System.out.println(Arrays.toString(numbers)); | |
| System.out.println(findPairs(numbers, 10)); | |
| } | |
| // Please try not to change anything in this method. | |
| public static void addRandomNumbers(int[] array) { | |
| for (int i = 0; i < array.length; i++) { | |
| array[i] = new Random().nextInt() % 10; | |
| } | |
| } | |
| // Try to complete this method. | |
| public static List<String> findPairs(int[] numbers, int desiredSum) { | |
| Arrays.sort(numbers); | |
| int a = 0; | |
| int b = numbers.length - 1; | |
| HashSet<Pair> pairHashSet = new HashSet<>(); | |
| for(int i = 0; i < numbers.length;i++){ | |
| if((numbers[a] + numbers[b] == desiredSum) && (a != b)) | |
| { | |
| Pair p = new Pair(); | |
| p.x = numbers[a]; | |
| p.y = numbers[b]; | |
| pairHashSet.add(p); | |
| a = a + 1; | |
| b = b - 1; | |
| } | |
| else if (numbers[a] + numbers[b] > desiredSum) | |
| { | |
| b = b - 1; | |
| } | |
| else | |
| { | |
| a = a + 1; | |
| } | |
| } | |
| System.out.println(pairHashSet); | |
| return null; | |
| } | |
| } | |
| //NAME : Aryan Dixit | |
| //SECTION : G | |
| //CLASS ROLL NUMBER : 35 | |
| //UNIVERSITY ROLL NUMBER : 191500156 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
ctrl+alt+shift+Lto properly format your code in IntelliJ.varkeyword for "Local Variable Type Inferencing".Here is a formatted version of your code