Home >Web Front-end >JS Tutorial >JavaScript Fun Question: Turtle Racing

JavaScript Fun Question: Turtle Racing

黄舟
黄舟Original
2017-02-04 15:37:241065browse

Two turtles, named A and B, are racing.

A is traveling at a speed of 720 feet per hour.

Young B knows that A must run slower than it, so it is still eating vegetables calmly.

When B starts running, it finds that A is already 70 feet ahead, but B's speed is 850 feet per hour, so it can definitely catch up.

Excuse me, how long does it take for B to catch up with A?

More general situation: given two speeds v1 (speed of A, integer of >0), v2 (speed of B, integer of >0), and a leading gap g (g> ;0), how long does it take for B to catch up with A?

The result should be an array, [h, mn, s], h, mn, s represents hours, minutes and seconds.

If an abnormal situation occurs, such as v1 >= v2, so that B can never catch up with A, then null will be returned directly.

For example:

race(720, 850, 70) // => [0, 32, 18]  
race(80, 91, 37)   // => [3, 21, 49]

There are two key points in this question:

First of all, we must clarify the relationship. During the process of B chasing A, A has never been idle. , did not stop!

So if you want B to catch up with A, you must satisfy this equation:

v1 * time + g = v2 * time

It is very simple to find time in this way, But the most critical thing is how to split time into hours, minutes and seconds.

My approach is to find the clock first, find the minutes based on the remainder, and then find the seconds based on the remainder.

function race(v1, v2, g) {  
    var h = -1;  
    var mn = -1;  
    var s = -1;  
    var remainder;  
    var speedGap = v2 - v1;  
    if(speedGap > 0){  
        remainder = g % speedGap;  
        h = parseInt(g / speedGap);  
        mn = parseInt(60 * remainder / speedGap);  
        remainder = remainder * 60 % speedGap;  
        s = parseInt(remainder * 60 / speedGap);  
        return [h, mn, s];  
    }  
    return null;  
}

The above is the content of JavaScript Fun Question: Turtle Race. For more related content, please pay attention to the PHP Chinese website (www.php.cn)!


Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn