diff --git a/app/services/group_stage_service.rb b/app/services/group_stage_service.rb index 4a70f37..aa2b37e 100644 --- a/app/services/group_stage_service.rb +++ b/app/services/group_stage_service.rb @@ -143,10 +143,9 @@ class GroupStageService teams_per_group_ranked_transposed = teams_per_group_ranked.transpose first_places = teams_per_group_ranked_transposed[0] second_places = teams_per_group_ranked_transposed[1] - # split the second places in half and place the second half at the beginning - # e.g. [1, 2, 3, 4, 5, 6] to [4, 5, 6, 1, 2, 3] - mid = second_places.length / 2 - second_places_new_order = second_places[mid..-1] + second_places[0..mid] + + second_places_new_order = split_and_rotate(second_places) + # zip the first and second places together # e.g. [1, 2, 3], [a, b, c] to [1, a, 2, b, 3, c] first_places.zip(second_places_new_order).flatten diff --git a/app/services/utils.rb b/app/services/utils.rb index 9a53daf..ed52efe 100644 --- a/app/services/utils.rb +++ b/app/services/utils.rb @@ -29,4 +29,17 @@ class Utils def self.po2?(number) number.to_s(2).count('1') == 1 end + + # split the array in half and place the second half at the beginning + # e.g. [1, 2, 3, 4, 5, 6] to [4, 5, 6, 1, 2, 3] + def split_and_rotate(array) + # handle the case where the array has an odd number of elements + middle_element = [] + if array.length.odd? + # pop the last element and place it in the middle + middle_element = [array.pop] + end + mid = array.length / 2 + array[mid..-1] + middle_element + array[0..mid] + end end diff --git a/spec/services/utils_spec.rb b/spec/services/utils_spec.rb index f1c9ef5..1db709a 100644 --- a/spec/services/utils_spec.rb +++ b/spec/services/utils_spec.rb @@ -47,4 +47,20 @@ RSpec.describe Utils do expect(Utils.po2?(parameters[:test])).to eq(parameters[:result]) end end + + describe '#split_and_rotate' do + [ + { test: [1, 2, 3, 4, 5, 6], result: [4, 5, 6, 1, 2, 3] }, + { test: [1, 2, 3, 4, 5], result: [3, 4, 5, 1, 2] }, + { test: [1, 2, 3, 4], result: [3, 4, 1, 2] }, + { test: [1, 2, 3], result: [2, 3, 1] }, + { test: [1, 2], result: [2, 1] }, + { test: [1], result: [1] }, + { test: [], result: [] } + ].each do |parameters| + it "splits and rotates #{parameters[:test]} to #{parameters[:result]}" do + expect(Utils.new.split_and_rotate(parameters[:test])).to eq(parameters[:result]) + end + end + end end