iT邦幫忙

2021 iThome 鐵人賽

DAY 14
0
自我挑戰組

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

好想中樂透啊,Ruby 30 天刷題修行篇第十四話

嗨我是A Fei,連續好幾天都十一點多回家,真的是累翻,先來看看今天的題目:


Time to win the lottery!

Given a lottery ticket (ticket), represented by an array of 2-value arrays, you must find out if you've won the jackpot.

Example ticket:

[ [ 'ABC', 65 ], [ 'HGR', 74 ], [ 'BYHT', 74 ] ]
To do this, you must first count the 'mini-wins' on your ticket. Each subarray has both a string and a number within it. If the character code of any of the characters in the string matches the number, you get a mini win. Note you can only have one mini win per sub array.

Once you have counted all of your mini wins, compare that number to the other input provided (win). If your total is more than or equal to (win), return 'Winner!'. Else return 'Loser!'.

All inputs will be in the correct format. Strings on tickets are not always the same length.


一個字符串和一個數字
題目出了個樂透的小遊戲,它提供一組陣列,裡面包了好幾張「樂透票」,是由一個字串和一個數字組合而成,如果字串中有任何字元的編碼與數字匹配,將獲得小獎。注意,每子陣列只能獲得一次小獎。計算完贏得小獎的次數後,將該數字與另一組數字「win」比較,如果您的總數大於或等於「win」,則回傳 Winner,反之回傳 Loser。

def bingo(ticket,win)
  mini_win = 0
  for subarray in ticket
    if subarray[0].chars.map { |n| n.bytes }.flatten.include?(subarray[1])
    mini_win += 1
    end  
  end
  mini_win >= win ? "Winner!" : "Loser!" 
end

對比最佳解答:

def bingo(ticket, win)
  ticket.count { |string, code| string.include?(code.chr) } >= win ? 'Winner!' : 'Loser!'
end

上一篇
浮點數和整數的計算,Ruby 30 天刷題修行篇第十三話
下一篇
歡迎進入 ip 的世界,Ruby 30 天刷題修行篇第十五話
系列文
從真「新」鎮出發!30天的刷題修行篇,讓寫程式成為新必殺技16

尚未有邦友留言

立即登入留言