Skip to content
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
35 changes: 35 additions & 0 deletions 03.bowling/y-bowling.rb
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
#!/usr/bin/env ruby
# frozen_string_literal: true

scores = ARGV[0].split(',')
shots = []

scores.each do |s|
shots << (s == 'X' ? 10 : s.to_i)
shots << 0 if shots.length < 18 && s == 'X'
end

frames = shots.each_slice(2).to_a

frames[9] += frames.pop if frames.length == 11
point = frames.each_with_index.sum do |frame, i|
Comment on lines +12 to +15

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change
frames = shots.each_slice(2).to_a
frames[9] += frames.pop if frames.length == 11
point = frames.each_with_index.sum do |frame, i|
frames = shots.each_slice(2).to_a
frames[9] += frames.pop if frames.length == 11
point = frames.each_with_index.sum do |frame, i|

こんなふうに改行した方が処理のグルーピングとしてわかりやすいように思いました

next_frame = frames[i + 1]
not_last_frame = i != 9
strilke = frame[0] == 10
spare = frame.sum == 10

if not_last_frame && strilke
if next_frame.length == 3
10 + next_frame[0..1].sum
elsif next_frame[0] == 10
10 + 10 + frames[i + 2][0]
else
10 + next_frame.sum
end
elsif not_last_frame && spare
frame.sum + next_frame[0]
else
frame.sum
end
Comment on lines +16 to +33

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

あくまで参考情報ですが、こんなふうに書くこともできます。

Suggested change
next_frame = frames[i + 1]
not_last_frame = i != 9
strilke = frame[0] == 10
spare = frame.sum == 10
if not_last_frame && strilke
if next_frame.length == 3
10 + next_frame[0..1].sum
elsif next_frame[0] == 10
10 + 10 + frames[i + 2][0]
else
10 + next_frame.sum
end
elsif not_last_frame && spare
frame.sum + next_frame[0]
else
frame.sum
end
next frame.sum if i == 9
next_frame = frames[i + 1]
strilke = frame[0] == 10
spare = frame.sum == 10
if strilke
if i == 8
10 + next_frame[0..1].sum
elsif next_frame[0] == 10
10 + 10 + frames[i + 2][0]
else
10 + next_frame.sum
end
elsif spare
frame.sum + next_frame[0]
else
frame.sum
end

ポイントは以下の通りです。

  • 最終フレームだけ特別扱いして(next frame.sum if i == 9)、21行目、29行目の条件分岐をシンプルにする
  • if next_frame.length == 3 が真になるのは9フレーム目しかないので、if i == 8 としてしまう(これは好みの問題かも)

Copy link
Owner Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

なるほど、確かに最終フレームを特別扱いするだけで、
そのほかのコードも理解しやすいように書けるようになっているのですね

特別な処理とそうでない処理を切り分けるというのはいろんなところで使えそうなので
使っていこうと思います!

end
puts point