Task 4 — Closest Values to Target
Objective
Create a function that receives three integer slices and a target value.
For each input slice, find the two values that are closest to the target.
Return one pair for each input slice.
Input
List 1
list1 := []int{
41, 19, 25, 74, 85, 36,
93, 47, 56, 76, 20, 39,
}
List 2
list2 := []int{
39, 43, 56, 66, 32, 46,
58, 93, 74, 22, 81, 29,
}
List 3
list3 := []int{
93, 47, 74, 29, 85, 36,
80, 27, 56, 66, 20, 31,
}
The fourth argument is the target value:
target := 30
Function
Create a function named:
FindClosestPair(...)
Conceptually:
FindClosestPair(
list1,
list2,
list3,
target,
)
returns:
[][]int
Distance
For every value:
value
calculate its absolute distance from the target:
distance = abs(value - target)
The two values with the smallest distances form the result pair for that list.
List 1
Target:
30
The closest relevant values are:
25 -> distance 5
36 -> distance 6
Therefore:
[]int{25, 36}
List 2
The closest values are:
29 -> distance 1
32 -> distance 2
The expected pair follows the ordering shown in the original task:
[]int{32, 29}
List 3
The closest values are:
31 -> distance 1
27 -> distance 3
The expected pair is:
[]int{27, 31}
Expected Result
[][]int{
{25, 36},
{32, 29},
{27, 31},
}
Pair Ordering
The original expected result does not order each pair by distance from the target.
For example:
{32, 29}
places 32 before 29 even though 29 is closer to 30.
Similarly:
{27, 31}
places 27 before 31.
This suggests that the pair should preserve the relative order in which the selected values appeared in the original input slice.
Therefore, after selecting the two closest values, return them in their original slice order.
Tie Handling
A general implementation must define behavior when more than two values have the same distance from the target.
For deterministic behavior, use the original index as the secondary criterion.
Conceptually, candidates are ranked by:
1. absolute distance from target
2. original index
After selecting the two closest elements, return them in their original source order.
Requirements
For each input slice:
- calculate the distance of every element from the target
- identify the two elements with the smallest distances
- preserve their original relative order
- return them as a two-element slice
The complete result contains one pair for each input collection.
Input Validation
Each input slice must contain at least two elements.
If a slice contains fewer than two elements, a valid pair cannot be produced.
The implementation should explicitly handle or reject such input.
Implementation Notes
The selected elements do not need to be adjacent.
The term “pair” in this task means the two values closest to the target, not two neighboring elements in the source slice.