Adjust scores between adjacent students

by oktaviardi pratama

HTML

Given an array of integers (e.g., [1, 6, 3, 4, 3, 5]), the rules are:
<br>
If a student is between two students who both have lower scores, decrease their score by 1.
<br>
If a student is between two students who both have higher scores, increase their score by 1.
<br>
First and last students are never modified (no two neighbors).

JavaScript

$(document).ready(function() {

  function print(arr) {
    let newVal = [...arr];
    let flag;

    do {
      flag = 0;
      let temp = [...newVal]; // Work on a fresh copy each loop
      for (let i = 1; i < newVal.length - 1; i++) {
        if (newVal[i - 1] < newVal[i] && newVal[i + 1] < newVal[i]) {
          temp[i] = newVal[i] - 1;
          flag++;
        } else if (newVal[i - 1] > newVal[i] && newVal[i + 1] > newVal[i]) {
          temp[i] = newVal[i] + 1;
          flag++;
        }
      }
      newVal = temp;
    } while (flag > 0);

    return newVal;
  }

  console.log(print([1, 6, 3, 4, 3, 5]));
});