My problem is perhaps trivial, but I cannot crack it. Let's say we have a list of numbers: [-1, -2, 1, 2, 8, 9, 13] and I need to find one that has smallest difference to given number (to positive or negative side), let's say 5. Is there a simple way to do this?
Asked
Active
Viewed 476 times
0
-
what have you already done and what did you get stuck with? – Random Guy Jan 28 '19 at 20:42
-
And another (Java this time): https://stackoverflow.com/questions/13318733/get-closest-value-to-a-number-in-array – smac89 Jan 28 '19 at 20:44
-
Questions asking for *homework help* **must** include a summary of the work you've done so far to solve the problem, and a description of the difficulty you are having solving it ([help], [ask]). – Zabuzard Jan 28 '19 at 20:49
2 Answers
3
numbers.stream()
.mapToInt(i -> i-targetNumber)
.map(Math::abs)
.min()
.get() + targetNumber;
Something like this?
Homework: Get negative numbers come out right too :)
Edit: I couldn't leave it... How about this:
numbers.stream()
.min((i1,i2) -> Math.abs(i1-target)-Math.abs(i2-target))
.get();

Robert Bräutigam
- 7,514
- 1
- 20
- 38
0
You can take your number and compare it with all the numbers in the list. Then if the partial difference is minor that the difference, you can store the number as result.
public class Home {
public static void main(String[] args) {
List<Integer> list = Arrays.asList(-1,-2,1,2,8,9,13);
Scanner s = new Scanner(System.in);
int number = s.nextInt();
int result = 0;
int differencePartial;
int difference = 1000;
for (Integer i : list) {
if (number > i)
differencePartial = number - i;
else
differencePartial = i - number;
if (differencePartial < difference) {
difference = differencePartial;
result = i;
}
}
System.out.println(result);
}
}

Cesare Fischetti
- 111
- 1
- 6