2024-08-01 18:27:41 +00:00
|
|
|
require_relative '../../extensions/tree_node_extension'
|
|
|
|
|
|
|
|
module Tables
|
|
|
|
class Distribution
|
|
|
|
def initialize(min_per_table:, max_per_table:)
|
|
|
|
@min_per_table = min_per_table
|
|
|
|
@max_per_table = max_per_table
|
2024-08-02 18:17:22 +02:00
|
|
|
@tables = {}
|
|
|
|
end
|
|
|
|
|
|
|
|
def tables
|
|
|
|
@tables.values.freeze
|
|
|
|
end
|
|
|
|
|
2024-08-02 18:42:24 +02:00
|
|
|
def deep_freeze
|
|
|
|
@tables.each_value(&:freeze)
|
|
|
|
@tables.freeze
|
|
|
|
freeze
|
|
|
|
end
|
|
|
|
|
|
|
|
def replace(table)
|
|
|
|
@tables[table.id] = table
|
|
|
|
end
|
|
|
|
|
|
|
|
def dup
|
|
|
|
super.tap do |new_distribution|
|
|
|
|
new_distribution.instance_variable_set(:@tables, @tables.dup)
|
|
|
|
end
|
|
|
|
end
|
|
|
|
|
2024-08-02 18:17:22 +02:00
|
|
|
def <<(array)
|
|
|
|
Table.new(array).tap do |table|
|
|
|
|
@tables[table.id] = table
|
|
|
|
end
|
2024-08-01 18:27:41 +00:00
|
|
|
end
|
|
|
|
|
|
|
|
def random_distribution(people)
|
2024-08-02 18:17:22 +02:00
|
|
|
@tables = {}
|
2024-08-01 18:27:41 +00:00
|
|
|
|
2024-08-02 18:17:22 +02:00
|
|
|
self << people.slice!(0..rand(@min_per_table..@max_per_table)) while people.any?
|
2024-08-02 18:42:24 +02:00
|
|
|
|
|
|
|
@tables.freeze
|
|
|
|
freeze
|
2024-08-01 18:27:41 +00:00
|
|
|
end
|
|
|
|
|
|
|
|
def discomfort
|
2024-08-02 18:17:22 +02:00
|
|
|
tables.map(&:discomfort).sum
|
2024-08-01 18:27:41 +00:00
|
|
|
end
|
|
|
|
|
|
|
|
def inspect
|
2024-08-02 18:17:22 +02:00
|
|
|
"#{tables.count} tables, discomfort: #{discomfort}"
|
2024-08-01 18:27:41 +00:00
|
|
|
end
|
|
|
|
|
|
|
|
def pretty_print
|
2024-08-02 18:17:22 +02:00
|
|
|
tables.map.with_index do |table, i|
|
2024-08-02 17:37:50 +02:00
|
|
|
"Table #{i + 1} (#{table.count} ppl): (#{table.discomfort}) #{table.map(&:full_name).join(', ')}"
|
2024-08-01 18:27:41 +00:00
|
|
|
end.join("\n")
|
|
|
|
end
|
|
|
|
|
|
|
|
def deep_dup
|
|
|
|
self.class.new(min_per_table: @min_per_table, max_per_table: @max_per_table).tap do |new_distribution|
|
2024-08-02 18:17:22 +02:00
|
|
|
tables.each do |table|
|
|
|
|
new_distribution << table.dup
|
|
|
|
end
|
2024-08-01 18:27:41 +00:00
|
|
|
end
|
|
|
|
end
|
|
|
|
|
|
|
|
def save!
|
|
|
|
ActiveRecord::Base.transaction do
|
|
|
|
arrangement = TablesArrangement.create!
|
|
|
|
|
|
|
|
records_to_store = []
|
|
|
|
|
|
|
|
tables.each_with_index do |table, table_number|
|
|
|
|
table.each do |person|
|
|
|
|
records_to_store << { guest_id: person.id, tables_arrangement_id: arrangement.id, table_number: }
|
|
|
|
end
|
|
|
|
end
|
|
|
|
|
|
|
|
Seat.insert_all!(records_to_store)
|
|
|
|
|
|
|
|
arrangement.update!(discomfort:)
|
|
|
|
end
|
|
|
|
end
|
|
|
|
end
|
|
|
|
end
|