iT邦幫忙

第 11 屆 iThome 鐵人賽

DAY 13
0
自我挑戰組

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

Day13 - Codewars 刷題

今日喉嚨微恙
講話比較小聲且無力
請多多包涵 ~"~


題目(Your order, please)

Your task is to sort a given string. Each word in the string will contain a single number. This number is the position the word should have in the result.

Note: Numbers can be from 1 to 9. So 1 will be the first word (not 0).

If the input string is empty, return an empty string. The words in the input String will only contain valid consecutive numbers.

Examples
"is2 Thi1s T4est 3a"  -->  "Thi1s is2 3a T4est"
"4of Fo1r pe6ople g3ood th5e the2"  -->  "Fo1r the2 g3ood 4of th5e pe6ople"
""  -->  ""
def order(words)
  # your code...
end

Test.assert_equals(order("is2 Thi1s T4est 3a"), "Thi1s is2 3a T4est")
Test.assert_equals(order("4of Fo1r pe6ople g3ood th5e the2"), "Fo1r the2 g3ood 4of th5e pe6ople")
Test.assert_equals(order(""), "", "Empty input should return empty string")

影片解題:


答案:

# Your order, please
def order(words)
  words.split.sort_by{ |x| x.chars.min }.join' '
end

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


上一篇
刷題的標題好難想 (沒梗了 XD)
下一篇
Day14 - Codewars 刷題
系列文
自我挑戰 Ruby 刷題 30 天31

尚未有邦友留言

立即登入留言