【问题标题】:Split An Array into sub arrays that each sub array sum value not exceed in JavaScript在 JavaScript 中将一个数组拆分为每个子数组总和值不超过的子数组
【发布时间】:2021-10-07 19:02:23
【问题描述】:

我想创建 [10,10,10,10,10,10,10,10,10,4,4,4] 的子数组,每个子数组的总和为大于100,所以结果应该是[[10,10,10,10,10,10,10,10,10,4,4],[4]]

我在下面尝试过,但不知道问题出在哪里

   const arr=[10,10,10,10,10,10,10,10,10,4,4,4]

  
    const result=[]

    let sum=0
    let temp=[]

    for(let i=0; i<arr.length;i++){
      if(sum+arr[i]<=100){
        sum+=arr[i]
        temp.push(arr[i])
      }else{
         result.push(temp)
         sum=0
         temp.length=0

         temp.push(arr[i])
         sum+=arr[i]
      }
    }

console.log(result) //[ [ 4 ] ]

【问题讨论】:

  • temp.length=0 更改为 temp = []

标签: javascript algorithm


【解决方案1】:

temp 推送到result 后,您需要创建一个新的temp 数组,不要将旧数组的长度设置为0,因为您在result 中有对该数组的引用。所以把temp.length = 0改成temp = []

在循环结束时,您需要将最终的 temp 推送到 result

const arr = [10, 10, 10, 10, 10, 10, 10, 10, 10, 4, 4, 4]
const result = []

let sum = 0
let temp = []

for (let i = 0; i < arr.length; i++) {
  if (sum + arr[i] <= 100) {
    sum += arr[i]
    temp.push(arr[i])
  } else {
    result.push(temp)
    sum = 0
    temp = []

    temp.push(arr[i])
    sum += arr[i]
  }
}

if (temp.length > 0) {
  result.push(temp);
}

console.log(result)

【讨论】:

    【解决方案2】:

    第一:不要使用temp.length=0

    第二:你不是在else 中创建一个新数组,所以基本上你是在编辑你在result 中推送的内容

    else里面,推入result后,直接使用temp = []

    最重要的是,您应该检查temp中是否还有其他项目以及循环结束,然后再推入result

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2017-02-14
      • 2020-11-30
      • 2021-12-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多