嗨我是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