Wednesday, June 13, 2007

Q10: Bouncing Ball

Q: a ball is dropped from 100 meters and bounce back to half of previous height. How many meters does it pass when it hits the ground at 10th time, and the height of it 10th bounce back?

A:


public class BallBounce {
/**
* Because the height is half of the previous one each bounce back,
* the height is divided by 2 each time.
* @param initHeight the initial height
* @param times the number of bounce back
* @return the height of bounce
*/
public static float getHeight(float initHeight, int times){
for(int i=0; i< times; i++){
initHeight /= 2;
}
return initHeight;
}

/**
* When ball hits ground n times, it bounces back n-1 time.
* Therefore, it passes initHeight plus the multiplication of 2 and height of each bounce.
* @param initHeight the initial height
* @param times the number that ball hits the ground
* @return the meters of the ball passed
*/
public static float getBallPass(float initHeight, int hitTimes){
float p = initHeight;
for(int i=0; i<(hitTimes-1); i++){
p += getHeight(initHeight, i+1)*2;
}
return p;
}

public static void main(String[] args) {
int times = 5;
System.out.println("When the ball hits 10th ground, it passes " + getBallPass(100, times) + " meters, and it bounces back " + getHeight(100, times));
}
}

result:
When the ball hits 10th ground, it passes 299.60938 meters, and it bounces back 0.09765625.

No comments: