I wrote the below code to solve a prep test, found online. The goal is to find the min absolute difference between numbers in an array.
function minimumAbsoluteDifference(arr: number[]): number {
// Write your code here
let res = 0
const length = arr.length
let diff : number
for (let i = 0; i < length; i++) {
for (let j = 0; j < length; j++) {
if (i !== j) {
diff = Math.abs(arr[i] - arr[j])
if (diff < res || res === 0)
res = diff
}
}
}
return res
}
i ran tests on Math.abs()
, and these days it is faster than a bitshift version... It seems that the only way to make this faster, is either with a reduce, or create a hash to optimize the nested array version.
Any ideas how to rewrite this with reduce()
?
for (let j = i+1;
Unclear ifreduce()
will improve performance or just reduce the amount of code.