iT邦幫忙

2021 iThome 鐵人賽

DAY 13
0
自我挑戰組

從真「新」鎮出發!30天的刷題修行篇,讓寫程式成為新必殺技系列 第 13

浮點數和整數的計算,Ruby 30 天刷題修行篇第十三話

  • 分享至 

  • xImage
  •  

大家好,我是 A Fei,大天要來解甚麼題目呢?讓我們看下去:
(題目來源:Codewars


A child is playing with a ball on the nth floor of a tall building. The height of this floor, h, is known.

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?

Three conditions must be met for a valid experiment:
Float parameter "h" in meters must be greater than 0
Float parameter "bounce" must be greater than 0 and less than 1
Float parameter "window" must be less than h.
If all three conditions above are fulfilled, return a positive integer, otherwise return -1.

Note:
The ball can only be seen if the height of the rebounding ball is strictly greater than the window parameter.

Examples:

- h = 3, bounce = 0.66, window = 1.5, result is 3

- h = 3, bounce = 1, window = 1.5, result is -1 

(Condition 2) not fulfilled).

題目給了一個情境:一個小孩正 n 層樓玩球。該樓層的高度為 h,他把球扔出窗外,球反彈到其三分之二的高度(bounce 等於 0.66)。 他的母親從離地 1.5 公尺的窗戶往外看。請問,媽媽會看到球在窗外經過多少次(包括球掉落和彈跳的時候)。此外,題目給了三個條件:

  1. h(公尺)是浮點數且必須大於 0
  2. bounce 必須大於 0 且小於 1
  3. 窗戶高度必須小於 h

如果以上三個條件都滿足,則回傳看到球的次數(整數),反之則回傳 -1

我的答案:

def bouncingBall(h, bounce, window)
  return -1 if h <= 0 || (bounce <= 0 && bounce >= 1) || window >= h 
  i = 1
  while h * bounce > window
    h = (h * bounce)
    i += 2
  end 
  i
end

上一篇
實用的 each_cons 方法,Ruby 30 天刷題修行篇第十二話
下一篇
好想中樂透啊,Ruby 30 天刷題修行篇第十四話
系列文
從真「新」鎮出發!30天的刷題修行篇,讓寫程式成為新必殺技16
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言