简体   繁体   中英

How can I rewrite this code without while loop?

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?

Here is my solution:

 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

The result I got is correct, but apparently, it's not efficient enough, because it takes some time to run everything. Any suggestions on how could I make it "better"?

You need to figure out x , the number of times the ball needs to bounce for its peak to be below the window:

h * (bounce ** x) = window

Solving for x , we get

bounce ** x = window / h
ln(bounce ** x) = ln(window / h)
x * ln(bounce) = ln(window / h)
x = ln(window / h) / ln(bounce)

This will give you the number of bounces after which the peak will be below the window. Multiply by 2 (because the ball comes up and comes back down, passing the window twice), and add 1 if, the first time, the ball is dropped from higher than the window:

 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))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM