javascript - 在有条件的数组中查找局部最大值 [JS]

标签 javascript arrays

我正在努力寻找满足以下代码挑战的解决方案,以满足所有要求并需要一些帮助:

     var ex1 = [5, 5, 2, 1, *4*, 2, *6*, 2, 1, 2, 7, 7];
               // {pos:[4,6], peaks:[4,6] }
     var ex2 = [3, 2, 3, *6*, 4, 1, 2, *3*, 2, 1, 2, 3];
               // {pos:[3,7], peaks:[6,3]}
 var plateau = [1, *2*, 2, 2, 1];
               // {pos:[1],peaks[2]}
  1. Find the local maxima or "peaks" of a given array but ignore local maxima at the beginning and end of the array.
  2. If there is a "plateau", return the position and value at the beginning of the "plateau."
  3. Any plateaus at beginning and end of the array should be ignored.

我提出的解决方案使用reduce函数来查看数组中当前元素之前和之后的元素。如果这些值小于当前元素的值,则当前元素是峰值。数组边缘的“峰值”将被忽略,因为它们不满足第一个或第二个标准。

function pickPeaks(array) {
  return array.reduce((res, curr, i, arr) => {
    if(arr[i-1] < curr && curr > arr[i+1]) {
      res["pos"] = res["pos"] ? res["pos"].concat([i]) : [i];
      res["peaks"] = res["peaks"] ? res["peaks"].concat([curr]) : [curr];
    } 
    return res;
  },{});
}

但是,该解决方案未能找到稳定点。

如果我将“右侧”条件逻辑更改为 curr >= arr[i+1] 它会找到稳定状态,但不会忽略“边缘”稳定状态,如下所示:

var plateau = [1, *2*, 2, 2, 1];
      correct // {pos:[1],peaks[2]}
    var ex1 = [5, 5, 2, 1, *4*, 2, *6*, 2, 1, 2, *7*, 7];
    incorrect // {pos:[4,6,7], peaks:[4,6,10]}

我在这里缺少什么?如何检查“高原”是否位于数组的边缘?

最佳答案

您可以添加一个 while 循环来结束平稳期。

function getLocalMaxima(array) {
    return array.reduce(function (r, v, i, a) {
        var j = i;
        while (v === a[++j]);
        if (a[i - 1] < v && (a[i + 1] < v || a[i + 1] === v && a[j] < v)) {
            r.pos.push(i);
            r.peaks.push(v);
        }
        return r;
    }, { pos: [], peaks: []});
}


var ex1 = [5, 5, 2, 1, 4, 2, 6, 2, 1, 2, 7, 7],  // { pos: [4, 6], peaks:[4, 6] }
    ex2 = [3, 2, 3, 6, 4, 1, 2, 3, 2, 1, 2, 3],  // { pos: [3, 7], peaks: [6, 3]}
    plateau = [1, 2, 2, 2, 1];                   // { pos: [1], peaks[2] }
    
console.log(getLocalMaxima(ex1));
console.log(getLocalMaxima(ex2));
console.log(getLocalMaxima(plateau));
.as-console-wrapper { max-height: 100% !important; top: 0; }

关于javascript - 在有条件的数组中查找局部最大值 [JS],我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48305975/

相关文章:

javascript - Angular2 和 ng2-charts 模块 :

javascript - D3js v5 分组条形图数据 x.domain 标签和数据分离

c# - 如何创建包含真实图像的字节数组?

javascript - 如何使用 HashMap 或数组映射返回总数最高的类别?

javascript - 有没有更简单或更清晰的方法来在 Javascript 中的对象数组中查找对象?

javascript - Mapbox 加载周围的图 block

javascript - 带有 React 或 Javascript 扩展的子类如何工作?

javascript - 如何在不使用 ng serve 的情况下为 Angular 5 应用程序提供服务?

java - 按名字和姓氏对多维字符串数组进行排序

javascript - AngularJs 发布请求获取错误