在给定的数组列表中查找最接近的数组[关闭]

问题描述 投票:0回答:1

给定变量中的数组列表,如何找到距离主数组最近的数组的索引?我需要一个函数,通过数组每个索引的数值来完成此操作,并且如果可能的话,还请记住数组的长度。

function findClosestArray(x, list){
     //Array comparing code here
}
let mainArr = [2237, 2192, 2234, 2223, 2196, 2279, 2160, 2123, 2063];
let otherArrays = [
     [1757, 1650, 1757, 1774, 1755, 1615, 1591, 1550]
     [1678, 1545, 1742, 1605, 1662, 1629, 1678, 1601]
];
let closestArr = findClosestArray(mainArr, otherArrays);
//Expected output: 0 or 1 (index of otherArrays)
javascript arrays list sorting numbers
1个回答
1
投票

OP 没有描述什么是“最接近的”。但是给定相同的数组长度,我们可以计算数组项之间的比率。比率越接近

1
,数组项就越相似。然后我们将所有比率求和为两个数组的接近程度的值,并从列表中找到最接近的数组。如果数组相同,则总和将等于数组的长度:

let mainArr = [2237, 2192, 2234, 2223, 2196, 2279, 2160, 2123];
let otherArrays = [
     [1757, 1650, 1757, 1774, 1755, 1615, 1591, 1550],
     [1678, 1545, 1742, 1605, 1662, 1629, 1678, 1601]
];

let closestArr = findClosestArray(mainArr, otherArrays);

console.log(closestArr);

function findClosestArray(arr, list){
    
    // get sum of ratios between array items
    const getHowClose = (arr,arr2) => arr.map((item,i) => item/arr2[i]).reduce((sum,item) => sum+item);

    const ratios = list.map(arr2 => getHowClose(arr, arr2));
    console.log(...ratios);

    // find index with the smallest average ratio
    return ratios.reduce((min, item, i) => !min || min[0] > item ? [item, i] : min, 0)[1];
        
}

© www.soinside.com 2019 - 2024. All rights reserved.