He drops the ball out of the window. The ball bounces (for example), to two-thirds of its height (a
bounce
of 0.66).His mother looks out of a window 1.5 meters from the ground.
How many times will the mother see the ball pass in front of her window (including when it's falling and bouncing?
这是我的解决方案:
function bouncingBall(h, bounce, window) {
let count = 0;
if (h < 0 || bounce <= 0 || window >= h) {
return -1;
} else {
count += 2
}
let jump = h * bounce
while (jump > window) {
jump *= bounce
count += 2;
}
return count - 1;
}
console.log(bouncingBall(3.0, 0.66, 1.5)) //3
我得到的结果是正确的,但显然,它的效率不够,因为它需要一些时间来运行所有内容。关于如何让它“更好”有什么建议吗?
最佳答案
您需要计算出x
,即球需要弹跳的次数才能使其峰值低于窗口:
h * (bounce ** x) = window
求解x
,我们得到
bounce ** x = window / h
ln(bounce ** x) = ln(window / h)
x * ln(bounce) = ln(window / h)
x = ln(window / h) / ln(bounce)
这将为您提供反弹次数,之后峰值将低于窗口。乘以 2(因为球上来又落下,两次经过 window ),如果第一次球从 window 上方掉落,则加 1:
function bouncingBall(h, bounce, window) {
const bounces = Math.floor(Math.log(window / h) / Math.log(bounce));
return bounces * 2 + (h > window ? 1 : 0);
}
console.log(bouncingBall(3.0, 0.66, 1.5))
关于javascript - 如何在没有 while 循环的情况下重写这段代码?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60809973/