首页 > 解决方案 > 从特定位置之间的数组中获取最大值

问题描述

我正在尝试从数组中返回最大值,但我只需要数组中某些位置的最大值:例如。

var array = [1,2,3,4,5] 并且我需要将 array[0] 到 array[2] 的最大值的总和相加到 array[3] 到 array[4] (所以totalScore = max(array[0] ... array[2]) + max(array[3] ... array[4])

有没有办法用 Math.max.apply 做到这一点?我的代码在下面+笔在这里:https ://codepen.io/stdobrescu/pen/mdJdBbG?editors=1111

  $("input[type='radio']").click(function() {
    var question = document.getElementsByClassName("toggle");
    var totalScore = 0;
    var questionValue = [0];  

    for (i = 0; i < question.length; i++) {
      if (question[i].type == "radio") {
        if (question[i].checked) { 
          questionValue[i] = parseInt(question[i].value, 10);
          }
        highestVal(questionValue);
        totalScore = calcScore(questionValue);
        questionValue = questionValue.filter(n=>n!==undefined);
        $("#score").html(totalScore);
      }
    }
  });

 function highestVal (valueArray){
  valueArray = valueArray.filter(n=>n!==undefined);
  console.log("This is the value array " + valueArray);
  var highestVal = Math.max.apply(null, valueArray);
  console.log("This is the highest value " + highestVal)
  return highestVal;
 }

 function calcScore (scoreArray){

   var sum = scoreArray.reduce((a, b) => a + b, 0)
   console.log("The Sum is "+ sum);
   return sum;
 }

单选按钮结构(值进入 questionValue 数组)

<div class="input-control">
          <input id="1" class="toggle" name="1" value=0 type="radio">
          <label for="1" class="btn"><span>0</span> I never take longer than 30 minutes to fall asleep.</label>
          <input id="2" class="toggle " name="1" value=1 type="radio">
          <label for="2" class="btn"><span>1</span> I take at least 30 minutes to fall asleep, less than half the time.</label>
          <input id="3" class="toggle" name="1" value=2 type="radio">
          <label for="3" class="btn"><span>2</span> I take at least 30 minutes to fall asleep, more than half the time.</label>
          <input id="4" class="toggle" name="1" value=3 type="radio">
          <label for="4" class="btn"><span>3</span> I take more than 60 minutes to fall asleep, more than half the time.</label>
        </div>

谢谢!

标签: javascriptarrays

解决方案


const sumMax = (arr, ...pos) => pos.map(p => Math.max(...arr.slice(p[0], ++p[1]))).reduce((p, c) => p + c)

const myArray = [1, 2, 3, 4, 5]
console.log(sumMax(myArray, [0, 2], [3, 4]))


根据 OP 评论更新

制作sumMax实时函数的一种方法是在每次添加新项目时更新主数组并调用sumMax更新后的数组(这不是性能优化的解决方案,我们有时会计算冗余的最大值和总和,请参阅动态编程)。为此,我们使用闭包

function liveSumMax (arr, ...pos) { // wrapper function
  const mainArray = arr
  const positions = pos
  const sumMax = (ar, ...ps) => ps.map(p => {
    let max = Math.max(...ar.slice(p[0], p[1] + 1))
    max = max > -Infinity ? max : 0
    return max
  }).reduce((p, c) => p + c)
  return (...items) => { // live function
    mainArray.push(...items) // update mainArray
    return sumMax(mainArray, ...positions)
  }
}

const myArray = [1, 2, 3, 4, 5]
const sumMax = liveSumMax(myArray, [0, 2], [3, 9]) // returns a function
console.log(sumMax()) // no new item
console.log(sumMax(10, 20))
console.log(sumMax(30, 40, 50, 60))


推荐阅读