Skip to content

Instantly share code, notes, and snippets.

@louy2
Created October 12, 2020 07:46
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save louy2/2dac54263cb60f6e41ed7fc50fbd818f to your computer and use it in GitHub Desktop.
Save louy2/2dac54263cb60f6e41ed7fc50fbd818f to your computer and use it in GitHub Desktop.
Find the nearest number @ JetBrain Academy
import java.util.*;
import java.util.stream.Collectors;
class DistNum {
public Integer distance;
public Integer num;
public DistNum(Integer distance, Integer num) {
this.distance = distance;
this.num = num;
}
}
public class Main {
public static void main(String[] args) {
// write your code here
// scan in input
var sc = new Scanner(System.in);
var l = new ArrayList<Integer>();
while (sc.hasNextInt()) {
l.add(sc.nextInt());
}
var n = l.remove(l.size() - 1);
// calculate distances
var dnl = new ArrayList<DistNum>();
for (var x : l) {
var diff = Math.abs(x - n);
var dn = new DistNum(diff, x);
dnl.add(dn);
}
// sort distances
dnl.sort(Comparator.comparing(dn -> dn.distance));
// show closest numbers
var minDistance = dnl.get(0).distance;
var closestNums = dnl.stream()
.filter(dn -> dn.distance.equals(minDistance))
.map(dn -> dn.num)
.sorted()
.collect(Collectors.toCollection(ArrayList::new));
// System.out.println(closestNums);
for (var i = 0; i < closestNums.size(); i++) {
System.out.print(closestNums.get(i)
+ (i == closestNums.size() - 1 ? "\n" : " "));
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment