javascript - 如何在没有 while 循环的情况下重写此代码?
问题描述
他把球扔出窗外。球弹跳(例如)到其高度的三分之二(a
bounce
为 0.66)。他的母亲从距离地面 1.5 米的窗户向外望去。
妈妈会看到多少次球从她的窗前经过(包括它下落和弹跳的时候?
这是我的解决方案:
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(因为球升起又落下,两次通过窗口),如果球第一次从高于窗口的位置落下,则加 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))
推荐阅读
- python - 我在使用 KPrototyping 聚类算法聚类分类和数值数据时遇到错误
- java - 将字符串拆分为第 n 个分隔符
- c - 从 MATLAB 命令 Maxon Motors EPOS2 电机控制器
- javascript - 我想根据我的过滤器更新面包屑
- javascript - 如何在带有 React Navigation 的 React Native 中以编程方式在 Android 上隐藏标签栏?
- azure-webjobs - ApplicationInsights customMetrics 数据不适用于 WebJob
- asp.net-mvc - 如何将方法转换为异步?
- javascript - Object.defineProperties 嵌套
- python - 基于边权重的 2 个节点之间的所有路径
- javascript - 在 Javascript 中查找标记的百分比