Created
October 12, 2020 07:46
-
-
Save louy2/2dac54263cb60f6e41ed7fc50fbd818f to your computer and use it in GitHub Desktop.
Find the nearest number @ JetBrain Academy
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.*; | |
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