Class: Pairs

Inherits:
Object
  • Object
show all
Defined in:
lib/pairs.rb

Defined Under Namespace

Classes: CleanRoom, NoSolutionError

Constant Summary collapse

MAX_ATTEMPTS =
10_000

Instance Attribute Summary collapse

Instance Method Summary collapse

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

#blockObject (readonly)

Returns the value of attribute block.



4
5
6
# File 'lib/pairs.rb', line 4

def block
  @block
end

#max_attemptsObject (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

#solutionObject



40
41
42
# File 'lib/pairs.rb', line 40

def solution
  @solution ||= solve!
end

#solve!Object

Raises:



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