-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy patheuc_module.js
48 lines (41 loc) · 1.17 KB
/
euc_module.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
var assert = require('assert')
/*
* @desc Function to calculate euclidean distance
* @param a reference vector
* @param b target vector
* @return calculated distance value
*/
const eucDistance = (a, b) => {
return a
.map((x, i) => Math.abs( x - b[i] ) ** 2) // square the difference
.reduce((sum, now) => sum + now) // sum
** (1/2)
}
/*
* @desc Function to calculate euclidean distance by batch
* @param a reference vector
* @param b target array of vector
* @param s size of return array
* @return sorted distance
*/
const calcDistBatch = (a, b, s) => {
assert(a.length > 0)
assert(b.length > 0)
assert(s > 0)
let calcArray = []
for (var i=0; i<b.length; i++) {
calcArray.push(eucDistance(a, b[i]))
}
var sortedIndex = Array.from(Array(calcArray.length).keys())
.sort((a, b) => calcArray[a] < calcArray[b] ? -1 : (calcArray[b] < calcArray[a]) | 0)
let act_size = size => size <= sortedIndex.length ? size : sortedIndex.length
let ret_val = []
for (var i=0; i<act_size(s); i++) {
ret_val.push({
coor: b[sortedIndex[i]],
dist: calcArray[sortedIndex[i]]
})
}
return ret_val
}
module.exports = calcDistBatch