diff --git a/app/services/tables/distribution.rb b/app/services/tables/distribution.rb index b361c70..48d4ea9 100644 --- a/app/services/tables/distribution.rb +++ b/app/services/tables/distribution.rb @@ -13,9 +13,10 @@ module Tables end def random_distribution(people) - @tables = [] - - @tables << Table.new(people.slice!(0..rand(@min_per_table..@max_per_table))) while people.any? + min_tables = (people.count * 1.0 / @max_per_table).ceil + max_tables = (people.count * 1.0 / @min_per_table).ceil + @tables = people.in_groups(rand(min_tables..max_tables), false) + .map { |group| Table.new(group) } end def discomfort diff --git a/spec/services/tables/distribution_spec.rb b/spec/services/tables/distribution_spec.rb new file mode 100644 index 0000000..df88a85 --- /dev/null +++ b/spec/services/tables/distribution_spec.rb @@ -0,0 +1,25 @@ +# Copyright (C) 2024 Manuel Bustillo + +require 'rails_helper' + +module Tables + RSpec.describe Distribution do + describe '#random_distribution' do + let(:subject) { described_class.new(min_per_table: 5, max_per_table: 10) } + + context 'when there are fewer people than the minimum per table' do + it 'creates one table' do + subject.random_distribution([1, 2, 3, 4]) + expect(subject.tables.count).to eq(1) + end + end + + context 'when there are more people than the maximum per table' do + it 'creates multiple tables' do + subject.random_distribution([1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11]) + expect(subject.tables.count).to be > 1 + end + end + end + end +end