Find the nearest number
# Topic
ArrayList
# Problem
Find the nearest number
Write a program that finds the elements in an array of integers that are closest to a given integer. If you find several integers with the same distance to the N, you should output all of them in the ascending order. If there are several equal numbers, output them all.
Input: a set of integers and a number N.
Output: some number(s) from the given array.
Sample Input 1:
1 2 4 5
3
2
Sample Output 1:
2 4
Sample Input 2:
1 2 3 4
6
2
Sample Output 2:
4
Sample Input 3:
5 1 3 3 1 5
4
2
Sample Output 3:
3 3 5 5
# Hint & Explain
You need to use methods we haven't been taught (in my opinion, this makes this a bad problem), you should use
Collections.sort()
which sorts a collection, and alsoMath.abs(a)
which returns absolute value of a (if it is positive, it is the same, if it is negative it becomes the positive equivalent).We were also not taught how to approach a complicated problem like this, it is not good to just throw us into this with only the advanced users already understanding what they need to do, lastly there was some poor wording in the question, especially with the word "distance". I would recommend either avoiding problems like this or teaching us everything we need to understand before giving it to us, it took me a long time to figure out a lot of this because I had to learn on my own, go scrambling around the internet to understand the necessary information when it could have been taught in a topic.
That is relatively complex task, not trivial at least. Good thing is however you can split it to several trivial task and implement them one after another.
- input data: you've got a line of integers and yet another one in a separate line. Get the first line as a string, split it by spaces to array, get from each sub-string an integer and put it in int[] array or ArrayList or any storage of your preference. Just get the number N on the next line.
- distance: means you need to find a minimal distance between N and numbers in array. It could be 0 or anything. Trick here if you just get the difference between number in array and N it could be positive or negative, depends from what side number is closer to N. Somehow you need to get rid off the sign, the absolute value you are interested in.
- find all nearest numbers: you have your distance, find all numbers in array with exactly this distance from N and store them some were, ArrayList wouldn't be overkill here.
- sort and output: task requires output in ascending order, just sort and print your favorite way
Neither of this sub task requires you to know what you haven't taught yet till that point. If you lazy enough to write your own abs() function here, use
Math.abs()
instead - it is proven to work since Java's childhood )
Useful link: https://stackoverflow.com/questions/1187352/find-closest-value-in-an-ordered-list
# Solution
# My solution
// I don't even have the capacity to solve this problem
# Other solution 1
import java.util.*;
public class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
String[] items = scanner.nextLine().split("\\s+");
List<Integer> numbers = new ArrayList<>();
for (String item : items) {
numbers.add(Integer.parseInt(item));
}
int n = scanner.nextInt();
ArrayList<Integer> result = new ArrayList<>();
int delta = Integer.MAX_VALUE;
for (int i : numbers) {
if (Math.abs(i - n) < delta) {
delta = Math.abs(i - n);
result.clear();
result.add(i);
} else if (Math.abs(i - n) == delta) {
result.add(i);
}
}
Collections.sort(result);
for (int item : result) {
System.out.print(item + " ");
}
}
}
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
# Other solution 2
import java.util.ArrayList;
import java.util.Collections;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
var list = new ArrayList<Integer>();
while (scanner.hasNextInt()) {
list.add(scanner.nextInt());
}
var n = list.remove(list.size() - 1);
Collections.sort(list);
var closest = Integer.MAX_VALUE;
for (Integer element : list) {
if (Math.abs(n - element) < closest) {
closest = Math.abs(n - element);
}
}
for (Integer element : list) {
if (Math.abs(n - element) == closest) {
System.out.print(element + " ");
}
}
}
}
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
# Other solution 3
import java.util.*;
import java.util.stream.Collectors;
public class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
String line = scanner.nextLine();
String[] numbers = line.split("\\s+");
List<Integer> nums = Arrays.stream(numbers).map(Integer::parseInt).sorted().collect(Collectors.toList());
int minimumDistance = Integer.MAX_VALUE;
int reference = scanner.nextInt();
for (int num: nums) {
int distance = Math.abs(num - reference);
if (distance < minimumDistance) {
minimumDistance = distance;
}
}
for (int num: nums) {
if (Math.abs(num - reference) == minimumDistance) {
System.out.print(num + " ");
}
}
}
}
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
# Other solution 4
import java.util.*;
import java.util.stream.Collectors;
public class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
List<Integer> arrayNumber = Arrays.stream(scanner.nextLine().split(" "))
.map(Integer::parseInt)
.sorted()
.collect(Collectors.toList());
int n = scanner.nextInt();
int minDistance = arrayNumber.stream().mapToInt(e -> Math.abs(n - e)).min().orElseThrow();
arrayNumber.stream()
.filter(e -> Math.abs(n - e) == minDistance)
.forEach(e -> System.out.printf("%d ", e));
}
}
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19