Class: Mastermind::Game::Code
- Inherits:
-
Object
- Object
- Mastermind::Game::Code
- Defined in:
- lib/mastermind/game/code.rb
Instance Attribute Summary collapse
-
#sequence ⇒ Object
readonly
Returns the value of attribute sequence.
Class Method Summary collapse
Instance Method Summary collapse
- #==(code) ⇒ Object
- #color_counts ⇒ Object
- #color_matches_with(code) ⇒ Object
- #exact_matches_with(code) ⇒ Object
-
#initialize(sequence:) ⇒ Code
constructor
A new instance of Code.
- #length ⇒ Object
- #partial_matches_with(code) ⇒ Object
Constructor Details
Instance Attribute Details
#sequence ⇒ Object (readonly)
Returns the value of attribute sequence.
4 5 6 |
# File 'lib/mastermind/game/code.rb', line 4 def sequence @sequence end |
Class Method Details
Instance Method Details
#==(code) ⇒ Object
55 56 57 58 59 |
# File 'lib/mastermind/game/code.rb', line 55 def ==(code) code.is_a?(Code) && length == code.length && exact_matches_with(code) == length end |
#color_counts ⇒ Object
24 25 26 27 28 29 |
# File 'lib/mastermind/game/code.rb', line 24 def color_counts sequence.each_with_object({}) do |piece, counts| counts[piece.color] ||= 0 counts[piece.color] += 1 end end |
#color_matches_with(code) ⇒ Object
40 41 42 43 44 45 46 47 48 |
# File 'lib/mastermind/game/code.rb', line 40 def color_matches_with(code) raise ArgumentError unless code.is_a? Code other_colors = code.color_counts sum = 0 color_counts.each do |color, quantity| sum += [quantity, other_colors[color] || 0].min end sum end |
#exact_matches_with(code) ⇒ Object
31 32 33 34 35 36 37 38 |
# File 'lib/mastermind/game/code.rb', line 31 def exact_matches_with(code) raise ArgumentError unless code.is_a? Code sum = 0 sequence.each_with_index do |piece, idx| sum += 1 if piece == code.sequence[idx] end sum end |
#length ⇒ Object
20 21 22 |
# File 'lib/mastermind/game/code.rb', line 20 def length @sequence.length end |
#partial_matches_with(code) ⇒ Object
50 51 52 53 |
# File 'lib/mastermind/game/code.rb', line 50 def partial_matches_with(code) raise ArgumentError unless code.is_a? Code color_matches_with(code) - exact_matches_with(code) end |