Frog Jump Problem
A small frog wants to get to the other side of the road. The frog is currently located at position X and wants to get to a position greater than or equal to Y. The small frog always jumps a fixed distance, D.
Count the minimal number of jumps that the small frog must perform to reach its target.
HTML
<p>
A small frog wants to get to the other side of the road. The frog is currently located at position X and wants to get to a position greater than or equal to Y. The small frog always jumps a fixed distance, D.
Count the minimal number of jumps that the small frog must perform to reach its target.
</p>
<div>
X = <input id="X" type="text">
</div>
<div>
Y = <input id="Y" type="text">
</div>
<div>
D = <input id="D" type="text">
</div>
<div>
<button id="Calculate">Calculate Min Hops</button>
</div>
<div>
<div id="Result"></div>
</div>
CSS
div { line-height: 30px;}
JavaScript
function frogMinJumps(x,y,d) {
var numberOfJumps;
// Assume x,y and d are 1 .. 1,000,000,000
if (x < 1 || y < 1 || d < 1) {
return 'Values must be greater than 1';
}
if (x > 1000000000 || y > 1000000000 || d > 1000000000) {
return 'Values must be less than 1,000,000,000';
}
if ( (y-x) < d ) {
numberOfJumps = 1;
} else {
if ( (y-x) % d === 0) {
numberOfJumps = parseInt((y-x)/d);
} else {
numberOfJumps = parseInt(((y-x)/d)+1);
}
}
return numberOfJumps.toString();
}
document.querySelector('#Calculate').addEventListener('click', function(){
var x = parseInt(document.querySelector('#X').value);
var y = parseInt(document.querySelector('#Y').value);
var d = parseInt(document.querySelector('#D').value);
document.querySelector('#Result').textContent = frogMinJumps(x,y,d);
}, false);