Class: BracketGraph::Graph

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

Direct Known Subclasses

LoserGraph

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(root_or_size) ⇒ Graph

Builds a new graph. The graph will be composed by a root seat and a match with two seats pointing to the root seat Each seat will then follows the same template (seat -> match -> 2 seats) until the generated last level seats (the starting seats) is equal to ‘size`.

Parameters:

  • size (Fixnum|Seat)

    The number of orphan seats to generate, or the root node

Raises:

  • (ArgumentError)

    if size is not a power of 2



13
14
15
16
17
18
19
20
21
# File 'lib/bracket_graph/graph.rb', line 13

def initialize root_or_size
  if root_or_size.is_a? Seat
    @root = root_or_size
    update_references
  else
    raise ArgumentError, 'the given size is not a power of 2' if Math.log2(root_or_size) % 1 != 0
    build_tree root_or_size
  end
end

Instance Attribute Details

#rootObject (readonly)

Returns the value of attribute root.



3
4
5
# File 'lib/bracket_graph/graph.rb', line 3

def root
  @root
end

#seatsObject (readonly)

Returns the value of attribute seats.



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

def seats
  @seats
end

#starting_seatsObject (readonly)

Returns the value of attribute starting_seats.



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

def starting_seats
  @starting_seats
end

Instance Method Details

#[](position) ⇒ Object



23
24
25
# File 'lib/bracket_graph/graph.rb', line 23

def [](position)
  seats.detect { |s| s.position == position }
end

#as_json(*attrs) ⇒ Object



45
46
47
# File 'lib/bracket_graph/graph.rb', line 45

def as_json *attrs
  @root.as_json *attrs
end

#seed(teams, shuffle: false) ⇒ Object

Fills the starting seats with the given ‘teams`

Parameters:

  • teams (Array)

    Teams to place as payload in the starting seats

  • shuffle (true, false) (defaults to: false)

    Indicates if teams shoud be shuffled

Raises:

  • (ArgumentError)

    if ‘teams.count` is greater then `#size`



37
38
39
40
41
42
43
# File 'lib/bracket_graph/graph.rb', line 37

def seed teams, shuffle: false
  raise ArgumentError, "Only a maximum of #{size} teams is allowed" if teams.size > size
  slots = TeamSeeder.new(teams, size, shuffle: shuffle).slots
  starting_seats.sort_by(&:position).each do |seat|
    seat.payload = slots.shift
  end
end

#sizeObject

Number of the starting seats



28
29
30
# File 'lib/bracket_graph/graph.rb', line 28

def size
  starting_seats.size
end