iT邦幫忙

第 11 屆 iThome 鐵人賽

DAY 15
0
自我挑戰組

自我挑戰 Ruby 刷題 30 天系列 第 15

Day15 - Codewars 刷題

試著挑戰Codewars LV5 題目
看起來很簡單 但執行時會有錯誤
推斷是思考邏輯不正確導致特定情況下
原本寫法可以通過
遇到其他案例時會失敗
怕思考找問題會花太多時間
決定第二題解法下集待續 XD


題目(Find the divisors!)

Create a function named divisors/Divisors that takes an integer n > 1 and returns an array with all of the integer's divisors(except for 1 and the number itself), from smallest to largest. If the number is prime return the string '(integer) is prime' (null in C#) (use Either String a in Haskell and Result<Vec<u32>, String> in Rust).

Example:
divisors(12) # should return [2,3,4,6]
divisors(25) # should return [5]
divisors(13) # should return "13 is prime"
def divisors(n)
  #your code here
end

Test.assert_equals(divisors(15), [3,5])
Test.assert_equals(divisors(253), [11,23])
Test.assert_equals(divisors(24), [2,3,4,6,8,12])

題目(Double Cola)

Sheldon, Leonard, Penny, Rajesh and Howard are in the queue for a "Double Cola" drink vending machine; there are no other people in the queue. The first one in the queue (Sheldon) buys a can, drinks it and doubles! The resulting two Sheldons go to the end of the queue. Then the next in the queue (Leonard) buys a can, drinks it and gets to the end of the queue as two Leonards, and so on.

For example, Penny drinks the third can of cola and the queue will look like this:

Rajesh, Howard, Sheldon, Sheldon, Leonard, Leonard, Penny, Penny
Write a program that will return the name of the person who will drink the n-th cola.

Input
The input data consist of an array which contains at least 1 name, and single integer n which may go as high as the biggest number your language of choice supports (if there's such limit, of course).

Output / Examples
Return the single line — the name of the person who drinks the n-th can of cola. The cans are numbered starting from 1.

whoIsNext(["Sheldon", "Leonard", "Penny", "Rajesh", "Howard"], 1) == "Sheldon"
whoIsNext(["Sheldon", "Leonard", "Penny", "Rajesh", "Howard"], 52) == "Penny"
whoIsNext(["Sheldon", "Leonard", "Penny", "Rajesh", "Howard"], 7230702951) == "Leonard"
def who_is_next(names, r)
  #your code here
end

names = ["Sheldon", "Leonard", "Penny", "Rajesh", "Howard"]

Test.assert_equals(who_is_next(names, 1), "Sheldon")
Test.assert_equals(who_is_next(names, 52), "Penny")
Test.assert_equals(who_is_next(names, 7230702951), "Leonard")

影片解題:
錄完發現音樂背景聲也被錄進去了
聲音聽起來會比較小聲
可無視直接看 code 沒關係喔


答案:

# Find the divisors!
def divisors(n)
  return "#{n} is prime" if [*1...n].map{ |x| n.gcd(x) }.uniq[1..-1] == []
  [*1...n].map{ |x| n.gcd(x) }.uniq[1..-1]
end

# Double Cola
# 此法不正確
def who_is_next(names, r)
  len = names.length
  if r == 1
    "#{names[r-1]}"
  else
    "#{names[r % len]}"
  end
end

下集待續..

本文同步發布於 小菜的 Blog https://riverye.com/


上一篇
Day14 - Codewars 刷題
下一篇
Day16 - Codewars 刷題
系列文
自我挑戰 Ruby 刷題 30 天31

尚未有邦友留言

立即登入留言