EDIT: Here's a rephrase of the question for clarity (apologies for confusion):
QUESTION : Given an array limits and an array punct_arr where both are sorted, return an output array of values separation_index where separation_index[i] is the closest value in punct_arr to limits[i]. It follows that separation_index will be of the same size as limits.
So, say I have two arrays:
limits = [280, 560]
punct_arr = [5, 99, 151, 159, 255, 352, 462, 502, 519, 531, 556, 602]
Expected Outcome: [255, 556]
The outcome should always be the same length as the limits array.
Here's what I got so far:
for (var limit = 0; limit < limits.length; limit ) {
for (var punct = 0; punct < punct_arr.length; punct ) {
if (Math.abs(punct_arr[punct - 1] - limits[limit]) < (Math.abs(punct_arr[punct] - limits[limit])) && (Math.abs(punct_arr[punct] - limits[limit]) < (Math.abs(punct_arr[punct] - limits[limit 1])))) {
separation_index.push(punct_arr[punct-1]);
}
}
}
Thanks in advance!
CodePudding user response:
Here's one way. I just adjusted a bit your code.
const limits = [280, 560]
const punct_arr = [5, 99, 151, 159, 255, 352, 462, 502, 519, 531, 556, 602]
function closestLimits(limits, arr) {
const diff = []
const separation_index = []
let closest
for (var limit = 0; limit < limits.length; limit ) {
diff.length = 0
for (var punct = 0; punct < arr.length; punct ) {
var m = Math.abs(arr[punct] - limits[limit]);
diff.push(m)
if (m <= Math.min(...diff)) {
smallest = arr[punct]
}
}
separation_index.push(smallest);
}
return separation_index
}
console.log(closestLimits(limits, punct_arr))
CodePudding user response:
Here's a decomposed approach where we start writing at a high-level and define auxiliary helper functions along the way -
function closest (limits, inputs) {
return limits.map(v => closest1(v, inputs))
}
function closest1 (one, many) {
return many.reduce((r, v) =>
delta(r, one) < delta(v, one) ? r : v,
-Infinity
)
}
function delta (a, b) {
return Math.abs(a - b)
}
const limits = [280, 560]
const inputs = [5, 99, 151, 159, 255, 352, 462, 502, 519, 531, 556, 602]
console.log(closest(limits, inputs))
[ 255, 556 ]