function findMinNonAdjacentPair(a) {
var mins = [];
if (a.length < 5) return {error: "no solution, too few elements."};
if (a.some(isNaN)) return {error: "non-numeric values given."};
for (var i = 1; i < a.length - 1; i++) {
if (mins.length < 4 || a[i] < a[mins[3]]) {
for (var j = Math.min(mins.length - 1, 2); j >= 0; j--) {
if (a[i] >= a[mins[j]]) break;
mins[j+1] = mins[j];
}
mins[j+1] = i;
}
}
var result = {
sum: a[mins[mins.length-1]]*2+1
}
for (var j = 0; j < mins.length-1; j++) {
for (var k = j + 1; k < mins.length; k++) {
if (Math.abs(mins[j] - mins[k]) > 1) {
if (result.sum > a[mins[j]]+a[mins[k]]) {
result.sum = a[mins[j]]+a[mins[k]];
result.index1 = mins[j];
result.index2 = mins[k];
};
if (k < j + 3) return result;
break;
}
}
}
return result;
}
var input = document.getElementById('in');
var output = document.getElementById('out');
var select = document.getElementById('pre');
function process() {
var a = input.value.split(',').map(Number);
output.textContent = JSON.stringify(findMinNonAdjacentPair(a), null, 4);
}
select.onchange = function() {
input.value = select.value;
process();
}
input.oninput = process;
process();
Type comma-separated list of values (or select one):</br>
<input id="in" value="2, 2, 1, 2, 4, 2, 6"> <=
<select id="pre">
<option value="5, 2, 4, 6, 3, 7">5, 2, 4, 6, 3, 7</option>
<option value="1, 2, 3, 3, 2, 1">1, 2, 3, 3, 2, 1</option>
<option value="4, 2, 1, 2, 4">4, 2, 1, 2, 4</option>
<option value="2, 2, 1, 2, 4, 2, 6" selected>2, 2, 1, 2, 4, 2, 6</option>
</select>
</br>
Output:</br>
<pre id="out"></pre>