Class: Pairs

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

Defined Under Namespace

Classes: CleanRoom

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(max_attempts: 1000, &block) ⇒ Pairs

Returns a new instance of Pairs.



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

def initialize(max_attempts: 1000, &block)
  @max_attempts = max_attempts
  @block = block
end

Instance Attribute Details

#blockObject (readonly)

Returns the value of attribute block.



2
3
4
# File 'lib/pairs.rb', line 2

def block
  @block
end

#max_attemptsObject (readonly)

Returns the value of attribute max_attempts.



2
3
4
# File 'lib/pairs.rb', line 2

def max_attempts
  @max_attempts
end

Instance Method Details

#solutionObject



34
35
36
# File 'lib/pairs.rb', line 34

def solution
  @solution ||= solve!
end

#solve!Object



9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
# File 'lib/pairs.rb', line 9

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)

      next unless clean_room.__constraints__.all? { |constraint|
        constraint.call(these)
      }

      result << these

      these.each do |item|
        all.delete item
      end
    end

    return result
  end
end