首页 > 解决方案 > 如何在没有 while 循环的情况下重写此代码?

问题描述

他把球扔出窗外。球弹跳(例如)到其高度的三分之二(abounce为 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

我得到的结果是正确的,但显然它不够高效,因为运行所有内容都需要一些时间。关于如何使它“更好”的任何建议?

标签: javascriptoptimization

解决方案


您需要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))


推荐阅读