67 lines
1.6 KiB
Ruby
Raw Normal View History

2024-07-24 20:14:58 +02:00
module Tables
class Distribution
2024-07-24 20:37:14 +02:00
attr_accessor :tables
2024-07-24 20:14:58 +02:00
def initialize(min_per_table:, max_per_table:)
@min_per_table = min_per_table
@max_per_table = max_per_table
end
def random_distribution(people)
@tables = []
@tables << people.slice!(0..rand(@min_per_table..@max_per_table)) while people.any?
end
def discomfort
@tables.map do |table|
local_discomfort(table)
end.sum
end
def inspect
"#{@tables.count} tables, discomfort: #{discomfort}"
end
def pretty_print
@tables.map.with_index do |table, i|
"Table #{i + 1} (#{table.count} ppl): (#{local_discomfort(table)}) #{table.map(&:full_name).join(', ')}"
end.join("\n")
end
2024-07-24 20:37:14 +02:00
def deep_dup
self.class.new(min_per_table: @min_per_table, max_per_table: @max_per_table).tap do |new_distribution|
new_distribution.tables = @tables.map(&:dup)
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
2024-07-24 20:14:58 +02:00
private
def local_discomfort(table)
10 * (number_of_groups(table) - 1)
end
def number_of_groups(table)
2024-07-25 11:25:22 +02:00
table.map(&:affinity_groups).flatten.uniq.count
2024-07-24 20:14:58 +02:00
end
end
end