[英]How can I rewrite this code without while loop?
他把球扔出窗外。 球反彈(例如)到其高度的三分之二(
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))
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.