I have an array with some numbers
[0, 0.1, 0.2, 0.3, 0.6, 0.8, 1]
how do I remove numbers that are close to each other less than or equal to 0.2
threshold and put the average of those values instead,
so the above array becomes
[0.2, 0.8]
0.2
because [0, 0.1, 0.2, 0.3]
are close to each other so they become (0 + 0.1 + 0.2 + 0.3) / 4 = 0.2
0.8
because [0.6, 0.8, 1]
are close to each other so they become (0.6, 0.8, 1) / 2 = 0.8
2
Answers
In the case, that the only thing that matters is the difference to the next neighbour, it’s quite easy. See comments in the code …
You could do this by iterating over every element of the array and keeping a temporary
close
array. Ifclose
is empty, or the current element and the last element inclose
‘s difference is less than the threshold, then you can add it toclose
. If not, then averageclose
and add it to the output array. Note that floating point math gets a bit weird here, you can use this rounding trick.Note that in your question, the numbers
0
,0.1
,0.2
,0.3
all have a difference of less than0.2
, so they should be averaged together. Their average is1.5
, not2
.