Assign an ID to every table and use a hash to store them

This commit is contained in:
Manuel Bustillo 2024-08-02 18:17:22 +02:00
parent 1d28cfc527
commit 60b96ab82d
3 changed files with 28 additions and 16 deletions

View File

@ -2,37 +2,47 @@ require_relative '../../extensions/tree_node_extension'
module Tables
class Distribution
attr_accessor :tables
def initialize(min_per_table:, max_per_table:)
@min_per_table = min_per_table
@max_per_table = max_per_table
@tables = []
@tables = {}
end
def tables
@tables.values.freeze
end
def <<(array)
Table.new(array).tap do |table|
@tables[table.id] = table
end
end
def random_distribution(people)
@tables = []
@tables = {}
@tables << Table.new(people.slice!(0..rand(@min_per_table..@max_per_table))) while people.any?
self << people.slice!(0..rand(@min_per_table..@max_per_table)) while people.any?
end
def discomfort
@tables.map(&:discomfort).sum
tables.map(&:discomfort).sum
end
def inspect
"#{@tables.count} tables, discomfort: #{discomfort}"
"#{tables.count} tables, discomfort: #{discomfort}"
end
def pretty_print
@tables.map.with_index do |table, i|
tables.map.with_index do |table, i|
"Table #{i + 1} (#{table.count} ppl): (#{table.discomfort}) #{table.map(&:full_name).join(', ')}"
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|
new_distribution.tables = @tables.map(&:dup)
tables.each do |table|
new_distribution << table.dup
end
end
end

View File

@ -1,10 +1,12 @@
module Tables
class Table < Array
attr_writer :discomfort
attr_reader :id
def initialize(*args)
super
reset
@id = SecureRandom.uuid
end
def reset

View File

@ -14,8 +14,8 @@ module Tables
context 'when there are two tables with two people each' do
let(:initial_solution) do
Distribution.new(min_per_table: 2, max_per_table: 2).tap do |distribution|
distribution.tables << %i[a b].to_table
distribution.tables << %i[c d].to_table
distribution << %i[a b]
distribution << %i[c d]
end
end
@ -32,8 +32,8 @@ module Tables
context 'when there are two tables with three people each' do
let(:initial_solution) do
Distribution.new(min_per_table: 3, max_per_table: 3).tap do |distribution|
distribution.tables << %i[a b c].to_table
distribution.tables << %i[d e f].to_table
distribution << %i[a b c]
distribution << %i[d e f]
end
end
@ -55,9 +55,9 @@ module Tables
context 'when there are three tables with two people each' do
let(:initial_solution) do
Distribution.new(min_per_table: 2, max_per_table: 2).tap do |distribution|
distribution.tables << %i[a b].to_table
distribution.tables << %i[c d].to_table
distribution.tables << %i[e f].to_table
distribution << %i[a b]
distribution << %i[c d]
distribution << %i[e f]
end
end