Skip to content

Instantly share code, notes, and snippets.

@lostmarinero
Created January 14, 2014 18:47
Show Gist options
  • Save lostmarinero/8423523 to your computer and use it in GitHub Desktop.
Save lostmarinero/8423523 to your computer and use it in GitHub Desktop.
This was a challenge as posted on reddit: http://www.reddit.com/r/dailyprogrammer/comments/1undyd/010714_challenge_147_easy_sport_points/ The challenge: You must write code that verifies the awarded points for a fictional sport are valid. This sport is a simplification of American Football scoring rules. This means that the score values must be …
# 6 points for a "touch-down"
# 3 points for a "field-goal"
# 1 point for an "extra-point"; can only be rewarded after a touch-down. Mutually-exclusive with "two-point conversion"
# 2 points for a "two-point conversion"; can only be rewarded after a touch-down. Mutually-exclusive with "extra-point"
class Scoring
attr_reader :max_number_each, :scoring_values
attr_accessor :score, :counter
def initialize(score)
check_input(score)
@scoring_values = [3, 6, 7, 8]
@counter = Array.new(4, 0)
@max_number_each = get_max_values(score)
@valid = nil
check_if_equal(score)
end
def check_input(score)
raise ArgumentError if score.class != Fixnum
end
def get_max_values(score)
self.scoring_values.map { |point_value| check_max(point_value, score) }
end
def check_max(points, score)
score / points
end
def roll_over?
@counter.each_with_index do |counter_num, index|
if counter_num > self.max_number_each[index]
return @valid = false if index == 3
@counter[index] = 0
return @counter[(index + 1)] += 1
end
end
@counter[0] += 1
end
def scoring_play_to_points(num_scoring_plays, index)
self.scoring_values[index] * num_scoring_plays
end
def calculated_points
@counter.map.with_index {|each_scoring_play, sindex| scoring_play_to_points(each_scoring_play, sindex)}.reduce(:+)
end
def valid_score?(score)
return @valid = true if calculated_points == score
end
def check_if_equal(score)
while @valid.nil?
valid_score?(score)
roll_over?
end
puts(@valid ? "Valid Score" : "Invalid Score")
end
end
puts Scoring.new(5)
puts Scoring.new(25)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment