diff --git a/src/matcher.test.ts b/src/matcher.test.ts index 826a38d..104683e 100644 --- a/src/matcher.test.ts +++ b/src/matcher.test.ts @@ -20,15 +20,15 @@ describe("createMatches", () => { expect(pairs.every((pair) => pair.length === 2)).toBe(true); }); - test("홀수 인원일 때 마지막 조가 3인이 된다", () => { + test("홀수 인원일 때 한 조가 3인이 된다", () => { const participants = createParticipants(5); const history: MatchHistory = { matches: [] }; const pairs = createMatches(participants, history); expect(pairs).toHaveLength(2); - expect(pairs[0]).toHaveLength(2); - expect(pairs[1]).toHaveLength(3); + const lengths = pairs.map((p) => p.length).sort(); + expect(lengths).toEqual([2, 3]); }); test("1명일 때 빈 배열을 반환한다", () => { diff --git a/src/matcher.ts b/src/matcher.ts index f079ec7..e55654d 100644 --- a/src/matcher.ts +++ b/src/matcher.ts @@ -61,6 +61,18 @@ export function createMatches( const pairs: Participant[][] = []; let shuffled = shuffle(participants); + + // 홀수일 때 3인조 후보를 먼저 무작위로 선택 + let thirdMember: Participant | null = null; + if (shuffled.length % 2 === 1) { + const randomIndex = Math.floor(Math.random() * shuffled.length); + thirdMember = shuffled[randomIndex]; + shuffled = [ + ...shuffled.slice(0, randomIndex), + ...shuffled.slice(randomIndex + 1), + ]; + } + let attempts = 0; const maxAttempts = 100; @@ -79,9 +91,10 @@ export function createMatches( attempts = 0; } - // 홀수 처리: 마지막 사람을 마지막 조에 추가 - if (shuffled.length === 1 && pairs.length > 0) { - pairs[pairs.length - 1].push(shuffled[0]); + // 3인조 후보를 무작위 조에 추가 + if (thirdMember && pairs.length > 0) { + const randomPairIndex = Math.floor(Math.random() * pairs.length); + pairs[randomPairIndex].push(thirdMember); } return pairs;