Javascript 给定一组数据,最终实现三组的和相差最小

2021-03-23  本文已影响0人  孟大仙
var arr = [1,3,56,78,34,23,67,5,67,8,9,54,33,56]
function miniDif (arr) {
  arr.sort((a, b) => b-a)
  let newArr = []
  let cloum1Sum = cloum2Sum = cloum3Sum = 0

  for (let i = 0; i < arr.length; i++){

    // 处理前3个元素
    if (i < 3){
      newArr[i] = []
      newArr[i].push(arr[i])

      // 初始3列值
      switch (i) {
        case 0:
          cloum1Sum = arr[i]
        case 1:
          cloum2Sum = arr[i]
        case 3:
          cloum3Sum = arr[i]
      }
    } else { // 处理后面的元素
      // 判断那个数组之和最小
      let num = Math.min(cloum1Sum, cloum2Sum, cloum3Sum)

      // 判断那列的和最小就往那列追加元素
      if (num === cloum1Sum) {
        newArr[0].push(arr[i])
        cloum1Sum += arr[i]
      } else if (num === cloum2Sum){
        newArr[1].push(arr[i])
        cloum2Sum += arr[i]
      } else {
        newArr[2].push(arr[i])
        cloum3Sum += arr[i]
      }
    }
  }
  return newArr
}
console.log(miniDif([1,3,56,78,34,23,67,5,67,8,9,54,33,56]))
上一篇下一篇

猜你喜欢

热点阅读