Move array splitting and rotating to utils

This commit is contained in:
Daniel Schädler 2025-03-04 21:34:16 +01:00
parent 2e56ed8bd0
commit 6fcdeac054
3 changed files with 32 additions and 4 deletions

View File

@ -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

View File

@ -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

View File

@ -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