iT邦幫忙

第 12 屆 iThome 鐵人賽

DAY 4
0
自我挑戰組

Codewars Ruby Challenge in 30 Days系列 第 4

Codewars Ruby Challenge - Day 4/30

學習

  1. 思考切入點的重要性:發現太過在意「爸爸的年紀是兒子的二倍?」題目,變成去想爸爸、兒子每多1歲去比較一次,如果直接用結果去推運算方法(給 36 跟 7 如何變 22),其實可以很快解出
  2. 先把題目變成數學運算式:龍哥直接把題目變成「father + n = 2son + n」,以數學來看當我們要得到「n = XXX」,很自然就會得到 n 是「father -2 * son」

題目:

# 請計算在幾年後,爸爸的年紀是兒子的二倍?
def twice_as_old(father, son)
  # 實作內容
end

答案需為:

puts twice_as_old(36,7)   # 22
puts twice_as_old(65,30)  # 5
puts twice_as_old(42,21)  # 0
puts twice_as_old(22,1)   # 20
puts twice_as_old(29,0)   # 29

我的答案

def twice_as_old(father, son)
  result = 0
  while father != (son * 2)
    father += 1
    son += 1
    result += 1
  end
  result
end

思路:

  1. 想用迴圈做窮取法來解
  2. 透過 result 這個變數不斷累加 1,看數字到多少時 father 年紀會是 son 的兩倍,符合時回傳 result 值即可

龍哥建議的答案

def twice_as_old(father, son)
  father - 2 * son
end

上一篇
Codewars Ruby Challenge - Day 3/30
下一篇
Codewars Ruby Challenge - Day 5/30
系列文
Codewars Ruby Challenge in 30 Days30
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言