sample_rank_correlation.js

import sampleCorrelation from "./sample_correlation.js";

/**
 * [秩相关系数](https://en.wikipedia.org/wiki/Rank_correlation)是
 * 衡量两个数组之间单调关系强度的指标
 *
 * @param {Array<number>} x 第一个输入数组
 * @param {Array<number>} y 第二个输入数组
 * @returns {number} 样本秩相关系数
 */
function sampleRankCorrelation(x, y) {
    const xIndexes = x
        .map((value, index) => [value, index])
        .sort((a, b) => a[0] - b[0])
        .map((pair) => pair[1]);
    const yIndexes = y
        .map((value, index) => [value, index])
        .sort((a, b) => a[0] - b[0])
        .map((pair) => pair[1]);

    // 在这一步,我们有一个索引数组
    // 它从排序后的数字映射到它们的原始索引。我们反转
    // 它,使其成为排序后的目标索引数组。
    const xRanks = Array(xIndexes.length);
    const yRanks = Array(xIndexes.length);
    for (let i = 0; i < xIndexes.length; i++) {
        xRanks[xIndexes[i]] = i;
        yRanks[yIndexes[i]] = i;
    }

    return sampleCorrelation(xRanks, yRanks);
}

export default sampleRankCorrelation;