Class: MatchyMatchy::MatchResults

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

Overview

An object representing the results of the stable match algorithm.

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(targets:, candidates:) ⇒ MatchResults

Initializes the match results with an empty list of matches.

Parameters:

  • targets (Array<MatchyMatchy::Target>)

    Array of all possible targets

  • candidates (Array<MatchyMatchy::Candidate> Array of all possible candidates)

    andidates [Array<MatchyMatchy::Candidate> Array of all possible candidates



15
16
17
18
19
# File 'lib/matchy_matchy/match_results.rb', line 15

def initialize(targets:, candidates:)
  @targets = targets
  @candidates = candidates
  @matches = targets.map { |t| [t, MatchList.new(t.capacity)] }.to_h
end

Instance Attribute Details

#candidatesObject (readonly)

A list of match candidates.



8
9
10
# File 'lib/matchy_matchy/match_results.rb', line 8

def candidates
  @candidates
end

#targetsObject (readonly)

A list of match targets.



5
6
7
# File 'lib/matchy_matchy/match_results.rb', line 5

def targets
  @targets
end

Instance Method Details

#<<(match) ⇒ MatchyMatchy::MatchResults

Adds a match to the results.

Parameters:

  • match (MatchyMatchy::Match)

    A match to add

Returns:



25
26
27
28
# File 'lib/matchy_matchy/match_results.rb', line 25

def <<(match)
  @matches[match.target] << match
  self
end

#by_candidateHash<MatchyMatchy::Target, Array<MatchyMatchy::Candidate>>

Returns a hash where the keys are the candidates in the match, and the values are the targets selected for each candidate (or nil, if the algorithm was unable to place the candidate).

Returns:

  • (Hash<MatchyMatchy::Target, Array<MatchyMatchy::Candidate>>)


47
48
49
50
51
# File 'lib/matchy_matchy/match_results.rb', line 47

def by_candidate
  placements =
    by_target.to_a.flat_map { |t, cs| cs.map { |c| [c, t] } }.to_h
  candidates.map { |c| [c.object, placements[c.object]] }.to_h.freeze
end

#by_targetHash<MatchyMatchy::Target, Array<MatchyMatchy::Candidate>>

Returns a hash where the keys are the targets in the match, and the values are an ordered list of candidates for each target (if any). Targets are included even if no candidates could be matched there.

Returns:

  • (Hash<MatchyMatchy::Target, Array<MatchyMatchy::Candidate>>)


35
36
37
38
39
40
# File 'lib/matchy_matchy/match_results.rb', line 35

def by_target
  targets.
    map { |t| [t.object, @matches[t].map { |m| m.candidate.object }] }.
    to_h.
    freeze
end