@seregpie/nearest-neighbor-chain
v1.0.0
Published
Builds a hierarchy of clusters.
Maintainers
Readme
NearestNeighborChain
NearestNeighborChain(values, distance)
Builds a hierarchy of the clusters.
| argument | description |
| ---: | :--- |
| values | An iterable of the values to build the hierarchy of the clusters from. |
| distance | A function to calculate the distance between two values. The value pairs with the lowest distance build a cluster. |
Returns the clustered values as a nested array.
dependencies
setup
npm
npm install @seregpie/nearest-neighbor-chainES module
import NearestNeighborChain from '@seregpie/nearest-neighbor-chain';Node
let NearestNeighborChain = require('@seregpie/nearest-neighbor-chain');browser
<script src="https://unpkg.com/@seregpie/bron-kerbosch"></script>
<script src="https://unpkg.com/@seregpie/nearest-neighbor-chain"></script>The module is globally available as NearestNeighborChain.
usage
let array = [4, 90, 12, 61, 29];
let clusters = NearestNeighborChain(array, (a, b) => Math.abs(a - b));
// => [[29, [4, 12]], [90, 61]]Overlapping clusters are merged together.
let intersection = function(a, b) {
a = new Set(a);
b = new Set(b);
return [...a].filter(v => b.has(v));
};
let array = ['ac', 'ab', 'baab', 'aba', 'bc'];
let clusters = NearestNeighborChain(array, (a, b) => -intersection(a, b).length);
// => ['ac', 'bc', ['ab', 'baab', 'aba']]