High Lowe Guess Recursive
by vzufelt
HTML
<input type="textbox" value="251" id="value_to_find" />
<input type="button" value="Click Me" onclick='doGuess();' />
<p id="output"></p>
JavaScript
// Intialize variables
function doGuess() {
var array = Array.apply(null, {
length: 1000
}).map(Number.call, Number); // New array
var high_index = array.length;
var low_index = 0;
var v = document.getElementById('value_to_find').value;
var g = array.value;
document.getElementById('output').innerHTML = find_value(array, high_index, low_index, value_to_find) ;
}
function find_value(a, h, l, v) {
var output = '';
var guess_index = Math.floor((h - l) / 2);
var guess = a[guess_index];
output += "Guess:" + guess + " At index:" + guess_index;
document.getElementById("output").innerHTML = output;
if (guess == v) {
output += "Solution found at index " + g ;
return output;
}
if (guess > v) {
output += "Guess " + a[g] + " too high";
find_value(a, h, g, v);
}
if (guess < v) {
output += "Guess " + a[g] + " too low";
find_value(a, h, l, v);
}
}