【问题标题】:Group or chunk array with maximum sum limit具有最大和限制的组或块数组
【发布时间】:2020-11-18 17:17:37
【问题描述】:

我有一个这样的数组

const array = [{id: 1, size: 1}, {id: 2, size: 2}, {id: 3, size: 4}, {id: 4, size: 1}, {id: 5, size: 2}, {id: 6, size: 3}, ...]

我想用 size 属性的最大总和对这个数组进行分组或分块(每个索引的总大小不能大于4),

所以新数组应该是这样的:

  const newArray = [
    [{id:1, size: 1}, {id:2, size: 2}, {id:4, size: 1}],
    [{id:3, size: 4}],
    [{id:5, size: 3}],
    [{id:6, size: 4}],
    ...
  ]

【问题讨论】:

  • 如果您尝试过,可以分享您的代码吗?
  • 您没有指定单个元素的大小是否可以超过 4(以及如果可行的话如何处理这种情况)。您也没有说顺序是否对分块很重要。即,如果一系列元素的大小为1, 4, 3,“智能”算法可能会尝试将13 分块在一起,但它们不是连续的,所以如果顺序很重要,那是相关的。您真的应该尝试在原始帖子中提供所有要求,以消除来回。

标签: javascript algorithm group-by reduce chunks


【解决方案1】:

您可以通过查看每个插槽的总和来找到下一个插槽。

let array = [{ id: 1, size: 1 }, { id: 2, size: 2 }, { id: 3, size: 4 }, { id: 4, size: 1 }, { id: 5, size: 2 }, { id: 6, size: 3 }],
    sum = 4,
    result = array.reduce((r, o) => {
        const temp = r.find(a => a.reduce((s, { size }) => s + size, 0) + o.size <= sum);
        if (temp) temp.push(o);
        else r.push([o]);
        return r;
    }, []);

console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }

【讨论】:

    【解决方案2】:

    我的方式...

    const array = 
          [ { id: 1, size: 1 } 
          , { id: 2, size: 2 } 
          , { id: 3, size: 4 } 
          , { id: 4, size: 1 } 
          , { id: 5, size: 2 } 
          , { id: 6, size: 3 } 
        //  , ...
          ]
      , szMax  = array.reduce((t,c)=>Math.max(t,c.size),0)
      , temp   = array.map(e=>({...e}))
      , result = []
      ;
    while (temp.length > 0)
      {
      let sz = szMax
        , nv = []
        ;
      while( sz > 0 )
        {
        let idx = temp.findIndex(x=>x.size <= sz)
        if (idx===-1) break
        nv.push( temp[idx] )
        sz -= temp[idx].size
        temp.splice(idx,1)
        }
      result.push([...nv])
      nv = []
      }
    
    console.log( result )
    .as-console-wrapper{max-height:100% !important;top: 0;}

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2016-08-15
      • 1970-01-01
      • 2018-10-15
      • 2017-12-26
      • 1970-01-01
      • 2023-03-08
      • 1970-01-01
      相关资源
      最近更新 更多