首页 > 解决方案 > 基于多个嵌套值对嵌套数组进行排序的最佳方法

问题描述

我需要确定 [8, 10, 12] 的最经济组合以等于给定数字(8 到 60 之间)并将该组合存储在变量中以供以后使用。数字可以重复(8+8=16、10+10=20 等)。给定的数字将永远是偶数。组合超过给定数字 2 是可以接受的(例如给定数字是 14,可接受的组合是 8+8)。

我可以计算组合并将它们存储在嵌套数组中。然后,我可以在其中一个索引上对数组进行排序,这在许多情况下都可以解决问题。我已经尝试对数组进行一些条件排序,但结果不一致。

我的代码...

var combo = (num) => {
        var arr = [];
        let units = [8, 10, 12];
        for (let i = 0; i < units.length; i++) {
            arr.push([units[i],Math.floor(num / units[i]),num%units[i]]);
            } 
            console.log(arr);
    }; 


//combo(24);
//returns
//[[8, 3, 0],[10, 2, 4],[12, 2, 0]]

虽然第一个和第三个嵌套数组都是正确的,但第三个将是最经济和最理想的结果。

//combo(28)
//returns
//[[8, 3, 4],[10, 2, 8],[12, 2, 4]]

在这种情况下,第二个数组是期望的结果

//combo(42)
//returns
//[[8, 5, 2],[10, 4, 2],[12, 3, 6]]

在这种情况下,第三个数组是所需的结果,因为稍后将 6 替换为 8 将使给定的 num 超过 2 - 这是可接受的结果。

我的目标是首先隔离所需的结果并将其存储在单独的变量中或存储在数组内的一致位置(通过排序)以供以后使用。我已经发现了 1000 种不这样做的方法,但是,一个成功的方法让我逃脱了。当我在业余时间学习时,我会将我的 javascript 体验归类为“高级初学者”或“低中级”。我可能从错误的方向来处理这个问题,因此非常感谢任何指导。希望我对问题的描述是有道理的。提前致谢。

标签: javascriptarrays

解决方案


根据您的评论,最佳解决方案是因子最小且余数为零的解决方案,这是微不足道的。

如果没有找到这样的解决方案,我认为你想要的是首先对第二个字段进行降序排序(最小长度),然后对全长剩余部分的百分比进行排序,以最小化截断。考虑:

var combo = (length) => {
    var optimals    = [];
    var suboptimals = [];

    [8, 10, 12].forEach( (unit) => {
        let lengths = Math.floor(length / unit);
        let remainder = length % unit;
        let fraction  = remainder / unit ;

        if ( remainder == 0 )
            optimals.push( [unit, lengths] );
        else
            suboptimals.push( [unit, lengths, remainder, fraction] );
    } );

    // This only works as long as the original input list is sorted ascending
    // Because then we know the most optimal solution must be the one 
    // with the biggest factor so we can simply return the last solution
    if ( optimals.length > 0 )
        return optimals[ optimals.length - 1 ];

    // Else we sort the suboptimals
    suboptimals.sort( (a, b) => {
        return a[1] < b[1] ? -1 : // First on # of lengths descending
               a[1] > b[1] ?  1 : 
               a[3] > b[3] ? -1 : // Then on fraction ascending
               a[3] < b[3] ?  1 : 
               0;
      });  

    return suboptimals[0];
}; 

console.log( combo(24) );
console.log( combo(28) );
console.log( combo(42) );

印刷:

> Array [12, 2]
> Array [10, 2, 8, 0.8]
> Array [12, 3, 6, 0.5]

推荐阅读