Class: Pairs
- Inherits:
-
Object
- Object
- Pairs
- Defined in:
- lib/pairs.rb
Defined Under Namespace
Classes: CleanRoom, NoSolutionError
Constant Summary collapse
- MAX_ATTEMPTS =
10_000
Instance Attribute Summary collapse
-
#block ⇒ Object
readonly
Returns the value of attribute block.
-
#max_attempts ⇒ Object
readonly
Returns the value of attribute max_attempts.
Instance Method Summary collapse
-
#initialize(max_attempts: MAX_ATTEMPTS, &block) ⇒ Pairs
constructor
A new instance of Pairs.
- #solution ⇒ Object
- #solve! ⇒ Object
Constructor Details
#initialize(max_attempts: MAX_ATTEMPTS, &block) ⇒ Pairs
Returns a new instance of Pairs.
8 9 10 11 |
# File 'lib/pairs.rb', line 8 def initialize(max_attempts: MAX_ATTEMPTS, &block) @max_attempts = max_attempts @block = block end |
Instance Attribute Details
#block ⇒ Object (readonly)
Returns the value of attribute block.
4 5 6 |
# File 'lib/pairs.rb', line 4 def block @block end |
#max_attempts ⇒ Object (readonly)
Returns the value of attribute max_attempts.
4 5 6 |
# File 'lib/pairs.rb', line 4 def max_attempts @max_attempts end |
Instance Method Details
#solution ⇒ Object
40 41 42 |
# File 'lib/pairs.rb', line 40 def solution @solution ||= solve! end |
#solve! ⇒ Object
13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 |
# File 'lib/pairs.rb', line 13 def solve! clean_room.instance_exec(&block) max_attempts.times do all = clean_room.__items__.values.flatten result = [] until all.empty? these = all.sample(2) result << these these.each do |item| all.delete item end end return result if clean_room.__constraints__.all? { |constraint| result.all? { |pair| constraint.call(pair) } } end raise NoSolutionError end |