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]));
});
Please Whitelist JSFiddle in your content blocker.
Help keep JSFiddle free for always by one of two ways:
Whitelist JSFiddle in your content blocker (two clicks)
Go PRO and get access to additional PRO features →
Join the 4+ million users, and keep the JSFiddle dream alive.
Ad-free
All ads in the editor and listing pages are turned completely off.
Use pre-released features
You get to try and use features (like the Palette Color Generator) months before everyone else.
Fiddle collections
Sort and categorize your Fiddles into multiple collections.
Private collections and fiddles
You can make as many Private Fiddles, and Private Collections as you wish!
Console
Debug your Fiddle with a minimal built-in JavaScript console.