🐕
ボーナスドリンク問題を解いてみました
概要
ボーナスドリンク問題を解いてみました。
解答
question.rb
# frozen_string_literal: true
class Question
class << self
def solve(cnt)
answer = cnt
while cnt >= 3
answer += cnt / 3
cnt = (cnt / 3) + (cnt % 3)
end
answer
end
end
end
question_spec.rb
# frozen_string_literal: true
RSpec.describe Question do
describe '.solve' do
subject { described_class.solve(cnt) }
context 'ドリンクを0本購入する場合' do
let(:cnt) { 0 }
it { is_expected.to eq 0 }
end
context 'ドリンクを1本購入する場合' do
let(:cnt) { 1 }
it { is_expected.to eq 1 }
end
context 'ドリンクを3本購入する場合' do
let(:cnt) { 3 }
it { is_expected.to eq 4 }
end
context 'ドリンクを11本購入する場合' do
let(:cnt) { 11 }
it { is_expected.to eq 16 }
end
context 'ドリンクを100本購入する場合' do
let(:cnt) { 100 }
it { is_expected.to eq 149 }
end
end
end
感想
解析的に解けるらしいのですが、簡単なシミュレーションを使って解きました。数学(算数?)を得意になりたい。
Discussion