iT邦幫忙

第 12 屆 iThome 鐵人賽

DAY 27
0
自我挑戰組

Codewars Ruby Challenge in 30 Days系列 第 27

Codewars Ruby Challenge - Day 27/30

  • 分享至 

  • twitterImage
  •  

學習

  1. 拆解問題的能力:刷了不少題目後,發現現在更能把問題拆解成小項目,然後一個個用程式碼實現出來,像這次寫題目前就先列出下面:
    • 分兩個 count: counter_25, counter_50 當其中一個小於0就是 NO,不然就是 YES
    • 收 25 時,counter_25 +1
    • 收 50 時,counter_25 -1
    • 收 100 時,counter_25 -3 || counter_25 -1 && counter_50 -1
  2. 刷題前先簡單看個討論:刷題網站在 Codewars 上分成 test 與 attempt,前者只給 1, 2 個測試,後者就會給到 20 個左右。今天刷題不管怎麼看就是會有一個測試過不了,先是學到了原來刷題網站還是可以用「p」印出每次測試 input 的值,來檢查到底什麼情況下噴錯。結果一看,明明是測試檔有問題,後來在討論區發現非常多人反應。


題目:

The new "Avengers" movie has just been released! There are a lot of people at the cinema box office standing in a huge line. Each of them has a single 100, 50 or 25 dollar bill. An "Avengers" ticket costs 25 dollars.
Vasya is currently working as a clerk. He wants to sell a ticket to every single person in this line.
Can Vasya sell a ticket to every person and give change if he initially has no money and sells the tickets strictly in the order people queue?
Return YES, if Vasya can sell a ticket to every person and give change with the bills he has at hand at that moment. Otherwise return NO.

# 翻譯:某家電影院,賣一張門票是 25 元,只接受客戶給 25 元、50 元、100 元三種面額,假設從開店就沒有任何錢的情況下,如果店員能在服務完所有客人後中間都順利找錢就回傳 'YES' 否則 'NO'

def tickets(people)

end

答案需要過以下測試:

RSpec.describe "Vasya - Clerk" do
  it "ticket" do
    expect(tickets([25, 25, 50])).to eq('YES')
    expect(tickets([25, 100])).to eq('NO')
    expect(tickets([50, 100, 100])).to eq('NO')
  end
end

我的答案

def tickets(people)
  counter_25, counter_50 = 0, 0
  people.each do |pay|
    counter_25 += 1 if pay == 25
    
    if pay == 50
      counter_25 -= 1
      counter_50 += 1
    end
    
    if pay == 100
      if counter_25 >= 3
        counter_25 -= 3 
      else
        counter_25 -= 1
        counter_50 -= 1
      end
    end
  end

  if counter_25 < 0 || counter_50 < 0
    'NO'
  else
    'YES'
  end
end

思路:

  1. 分兩個 count: counter_25, counter_50 當其中一個小於0就是 NO,不然就是 YES
  2. 收 25 時,counter_25 +1,收 50 時,counter_25 -1
  3. 收 100 時,counter_25 -3 或是 counter_25 -1 && counter_50 -1,總要選擇一個做,所以先判斷 4. counter_25 是否 ≥ 3,是就選前者,否就選後者

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

尚未有邦友留言

立即登入留言