bouncingBall.js

Codewars 알고리즘 풀이


Problem

  • A child is playing with a ball on the nth floor of a tall building.
    • 한 아이가 고층 빌딩의 n층에서 공을 가지고 놀고 있다.
  • The height of this floor, h, is known.
    • 이 층의 높이는 h이다.
  • He drops the ball out of the window.
    • 아이가 창문 밖으로 공을 떨어뜨린다.
  • The ball bounces to two-thirds of its height(a bounce of 0.66).
    • 공의 바운스는 높이의 2/3이다.
  • His mother looks out of a window 1.5 meters from the ground.
    • 그 아이의 어머니는 땅에서 1.5미터 떨어진 창문 밖에서 보고 있다.
  • How many times will the mother see the ball pass in front of her window(including when it’s falling and bouncing)?
    • 공이 어머니의 창문 앞에서 통과하는 것을 몇 번이나 볼 수 있을까?
    • (떨어지거나 튀는 경우를 포함한다)
  • Float parameter ‘h’ in meters must be greater than 0.
    • 매개변수 ‘h’는 0보다 커야 한다.
  • Float parameter ‘bounce’ must be greater than 0 and less than 1.
    • 매개변수 ‘bounce’는 0보다 크고 1보다 작아야 한다.
  • Float parameter ‘window’ must be less than ‘h’.
    • 매개변수 ‘window’는 ‘h’보다 작아야 한다.
  • If all three conditions above the fulfilled, return a positive integer, otherwise return -1.
    • 위의 세 가지 조건이 모두 충족되면 양의 정수를 반환하고, 그렇지 않으면 -1을 반환한다.



Solution 01

function bouncingBall(h, bounce, window) {
  if (h <= 0 || bounce <= 0 || bounce >= 1 || window >= h) return -1;
  
  let seen = 0;
  
  while (h > window) {
    seen++;
    h *= bounce;
    
    if (h > window) {
      seen++;
    }
  }
  return seen;
}

bouncingBall(3.0, 0.66, 1.5);   // 3
bouncingBall(30.0, 0.66, 1.5);  // 15


Solution 02

function bouncingBall(h, bounce, window) {
  if (h <= 0 || bounce <= 0 || bounce >= 1 || window >= h) return -1;
  
  let seen = 1;
  
  while ((h *= bounce) > window) {
    seen += 2;
  }
  return seen;
}

bouncingBall(3.0, 0.66, 1.5);   // 3
bouncingBall(30.0, 0.66, 1.5);  // 15


Solution 03

function bouncingBall(h, bounce, window) {
  if (h <= 0 || bounce <= 0 || bounce >= 1 || window >= h) return -1;
  
  const bounceHeight = h * bounce;
  
  if (bounceHeight > window) {
    return 2 + bouncingBall(bounceHeight, bounce, window);
  } else {
    return 1;
  }
}

bouncingBall(3.0, 0.66, 1.5);   // 3
bouncingBall(30.0, 0.66, 1.5);  // 15