https://school.programmers.co.kr/learn/courses/30/lessons/12985
문제는 위의 링크로 들어가서 풀어볼 수 있습니다.
토너먼트로 진행되는 한 대회에서
항상 이기는 두 명의 플레이어 A, B가
몇번째 경기에서 만나는지 풀어내는 문제다.
총 플레이어의 수, A, B의 출전번호가 매개변수로 주어지고,
만나는 경기의 라운드를 return하는 문제다.
내가 풀어낸 방식은 다음과 같다.
문제의 예의 경우로 본다면
8명이 출전, A는 4번, B는 7번인 경우에서
4번이 만날 수 있는 선수는 아래와 같다.
1라운드 : 3번.
2라운드 : 1번 혹은 2번.
3라운드 : 4, 5, 6, 7 번 중 한 명.
때문에 3라운드에서 만나게 되고, 3을 return하면 된다.
이를 조로 나눈 방식으로 표현하게 된다면,
1라운드 : 3 4 중 승자가 다음 라운드 진출.
2라운드 : 1 2 3 4 중 승자가 다음 라운드 진출.
3라운드 : 1~8 중 승자가 다음 라운드 진출.
이런 방식으로 진행된다.
각 조를 배열로 만들고, 이를 리스트로 만들어
한 조에 A, B가 모두 있는 경우를 return하도록 했다.
코드는 아래와 같다.
using System;
using System.Collections.Generic;
class Solution
{
public int solution(int n, int a, int b)
{
List<int> list = new List<int>();
// 라운드 별 한 조의 인원.
int power = n;
while (power > 1)
{
power /= 2;
list.Add(power);
}
list.Sort();
List<List<int[]>> battleList = new List<List<int[]>>();
//각 조의 인원을 설정하는 과정.
for (int i = 0; i < list.Count; i++)
{
int length = list[i] * 2;
int[] array = new int[length];
List<int[]> arrList = new List<int[]>();
for (int j = 1; j <= n; j++)
{
int slicer = (j % length) - 1;
if (slicer < 0) slicer += length;
array[slicer] = j;
if ((j % length) == 0)
{
arrList.Add(array);
array = new int[length];
}
}
battleList.Add(arrList);
}
for (int i = 0; i < battleList.Count; i++)
{
for (int j = 0; j < battleList[i].Count; j++)
{
//같은 조에 두 명의 선수가 있는지 확인하는 과정.
bool hasA = false, hasB = false;
for (int k = 0; k < battleList[i][j].Length; k++)
{
if (battleList[i][j][k] == a) hasA = true;
else if (battleList[i][j][k] == b) hasB = true;
Console.Write(battleList[i][j][k] + ", ");
}
Console.WriteLine();
if (hasA && hasB)
{
return i + 1;
}
else if (hasA || hasB)
{
break;
}
}
Console.WriteLine();
}
int answer = 0;
return answer;
}
}