Skip to content
Open
Show file tree
Hide file tree
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
7 changes: 7 additions & 0 deletions 03.bowling/bowling.rb
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
#! /usr/bin/env ruby
# frozen_string_literal: true

require_relative './bowling_method'

frames = format_score(ARGV[0])
puts sum_score(frames)
61 changes: 61 additions & 0 deletions 03.bowling/bowling_method.rb
Original file line number Diff line number Diff line change
@@ -0,0 +1,61 @@
# frozen_string_literal: true

def to_int_scores(strings_scores)
converted_array = []
strings_scores.each do |score|
if score == 'X'
converted_array << 10
converted_array << 0
else
converted_array.push(score.to_i)
end
end
converted_array
end

def parse_scores(raw_scores)
scores = raw_scores.split(',')
int_scores = to_int_scores(scores)
# 10フレーム目でストライクかスペアを出すとframesの要素数が10以上になる。こうすることで10フレーム目のストライク、スペアの得点加算も通常と同じ処理で済むのでこの形にしてある
int_scores.each_slice(2).to_a
end

def strike?(frame)
frame[0] == 10
end

def spare?(frame)
frame[0] + frame[1] == 10
end

def calc_strike_bonus(index, frames)
next_index = index + 1
next_frame = frames[next_index]
if strike? next_frame
after_next_frame = frames[next_index + 1]
next_frame[0] + after_next_frame[0]
else
next_frame[0] + next_frame[1]
end
end

def calc_spare_bonus(index, frames)
next_index = index + 1
next_frame = frames[next_index]
next_frame[0]
end

def sum_score(frames)
total_score = 0
total_frames = 10
total_frames.times do |index|
frame = frames[index]
total_score += frame[0] + frame[1]
if strike?(frame)
total_score += calc_strike_bonus(index, frames)
elsif spare?(frame)
total_score += calc_spare_bonus(index, frames)
end
end
total_score
end