C# 코딩 테스트 정리

2024. 1. 15. 21:13C#

728x90
반응형

배열의 길이 가져오기

int[] arr -> arr.Length;

for문에서, for(int i = 0; i < arr.Length; i++)

 

 

break;

break;는 반복문에서 사용할 수 있다. for문, while문

 

string -> int 변환

매개변수가 string이고 반환 값이 int일 때,

int answer = int.Parse(s);

int answer = Conver.ToInt32(stringNumber);

long answer = Convert.ToInt64(new string(a));

int -> string 변환

string numString = n.ToString();

 

배열 선언하기

long[] answer = new long[n]; 여기서 [n]은 배열의 개수

 

foreach 반복문

foreach(char digitChar in numString){}

 

수학 루트 사용하기

using System;

double root = Math.Sqrt(long n);

 

배열 조작하기

using System; 사용,

Array.Sort(배열);

Array.Sort(answer, 0, count);

Array.Reverse(배열);

Array.Resize(ref answer, count);

 

String으로 받은 각 자리 숫자의 합 더하기

string numString = x.ToString();
foreach(char digitChar in numString)

{
        sumNumber += Convert.ToInt32(digitChar.ToString());

}

 


 

Q1. 딕셔너리 이용해서 입력값 재정렬

이름 내림차순, 이름 같을 시 번호로 내림차순

//input
3
kim 010-5555-1111
lee 010-4444-5555
park 010-1111-2222

 

A.

첫 번째 줄 전화번호부의 개수 입력 받기

using System;
using System.Collections.Generic;

class Program
{
    static void Main()
    {
        // 전화번호부의 개수를 입력받음
        int n = int.Parse(Console.ReadLine());

        // Dictionary를 사용하여 이름과 전화번호를 저장
        Dictionary<string, List<string>> phoneBook = new Dictionary<string, List<string>>();

        // 둘째 줄부터 전화번호부 정보를 입력받음
        for (int i = 0; i < n; i++)
        {
            string[] input = Console.ReadLine().Split(); //.Split();은 공백을 기준으로 나눔
            string name = input[0];
            string phoneNumber = input[1];

            // Dictionary에 이름이 이미 존재하는 경우 리스트에 추가
            if (phoneBook.ContainsKey(name))
            {
                phoneBook[name].Add(phoneNumber);
            }
            else
            {
                // Dictionary에 이름이 존재하지 않는 경우 새로운 리스트 생성 후 추가
                phoneBook[name] = new List<string> { phoneNumber };
            }
        }

        // 이름을 오름차순으로 정렬
        var sortedNames = new List<string>(phoneBook.Keys);
        sortedNames.Sort();

        // 정렬된 이름과 전화번호를 출력
        foreach (var name in sortedNames)
        {
            // 전화번호를 오름차순으로 정렬
            phoneBook[name].Sort();

            // 이름과 정렬된 전화번호를 출력
            foreach (var phoneNumber in phoneBook[name])
            {
                Console.WriteLine($"{name} {phoneNumber}");
            }
        }
    }
}

 

실행하면 다음과 같다.

 


 

Q2. 좌표를 이용한 사각형 자르기 -최대 최소 사각형 넓이 구하기

//input
5 7 2 //첫째 줄은 N(사각형의 세로), M(사각형의 가로), K(자르는 횟수)
2 1 //자르는 점의 좌표1 (x1, y1) = (2, 1)
6 4 //자르는 점의 좌표2 (x2, y2) = (6, 4)

 

A.

띄어쓰기로 입력된 입력 값 가져오기

첫 번째 줄 가져와서 빈 칸 기준으로 Split하여 배열로 담는다. 각각 n, m, k에 입력.

두 번째 줄 이후로는 x, y 값을 똑같이 빈 칸 기준으로 Split하여 배열에 담는다.

using System;
class Program
{
    static void Main()
    {
    // 첫째 줄 읽기
    string[] firstLine = Console.ReadLine().Split(' ');
    int n = int.Parse(firstLine[0]);
    int m = int.Parse(firstLine[1]);
    int k = int.Parse(firstLine[2]);

    // 둘째 줄부터 마지막 줄까지 읽기
    for (int i = 0; i < k; i++)
    {
        string[] coordinates = Console.ReadLine().Split(' ');
        int x = int.Parse(coordinates[0]);
        int y = int.Parse(coordinates[1]);

        // 읽은 값을 사용하여 작업 수행
        Console.WriteLine($"Received coordinates: ({x}, {y})");
    }
}

 

 

x, y 각각의 배열을 만들어서 이진 탐색으로 다음 값이 이미 있는 값 사이에 오름차순으로 들어가게 만들기

using System;

class Program
{
    static void Main()
    {
        // 첫째 줄 읽기
        string[] firstLine = Console.ReadLine().Split(' ');
        int n = int.Parse(firstLine[0]);
        int m = int.Parse(firstLine[1]);
        int k = int.Parse(firstLine[2]);

        // x와 y를 저장할 배열 생성
        int[] xArray = new int[k];
        int[] yArray = new int[k];

        // 둘째 줄부터 마지막 줄까지 읽기
        for (int i = 0; i < k; i++)
        {
            string[] coordinates = Console.ReadLine().Split(' ');
            int x = int.Parse(coordinates[0]);
            int y = int.Parse(coordinates[1]);

            // x와 y 값을 배열에 저장
            xArray[i] = x;
            yArray[i] = y;
        }

        // 배열 정렬
        Array.Sort(xArray);
        Array.Sort(yArray);

        // 정렬된 배열 출력
        Console.WriteLine("Sorted x values:");
        foreach (var x in xArray)
        {
            Console.Write(x + " ");
        }
        Console.WriteLine();

        Console.WriteLine("Sorted y values:");
        foreach (var y in yArray)
        {
            Console.Write(y + " ");
        }
        Console.WriteLine();
    }
}

 

 

x, y, 각각의 배열에서 인접한 수의 차이를 가진 배열을 각각 뽑아내기 resultX, resultY 배열

using System;

class Program
{
    static void Main()
    {
        // 첫째 줄 읽기
        string[] firstLine = Console.ReadLine().Split(' ');
        int n = int.Parse(firstLine[0]);
        int m = int.Parse(firstLine[1]);
        int k = int.Parse(firstLine[2]);

        // x와 y를 저장할 배열 생성
        int[] xArray = new int[k];
        int[] yArray = new int[k];

        // 둘째 줄부터 마지막 줄까지 읽기
        for (int i = 0; i < k; i++)
        {
            string[] coordinates = Console.ReadLine().Split(' ');
            int x = int.Parse(coordinates[0]);
            int y = int.Parse(coordinates[1]);

            // x와 y 값을 배열에 저장
            xArray[i] = x;
            yArray[i] = y;
        }

        // 배열 정렬
        Array.Sort(xArray);
        Array.Sort(yArray);

        // resultX와 resultY 배열 초기화
        int[] resultX = new int[k - 1];
        int[] resultY = new int[k - 1];

        // x와 y 배열의 인접한 수의 차이를 저장
        for (int i = 0; i < k - 1; i++)
        {
            resultX[i] = xArray[i + 1] - xArray[i];
            resultY[i] = yArray[i + 1] - yArray[i];
        }

        // resultX와 resultY 배열 출력
        Console.WriteLine("Differences in x values:");
        foreach (var diffX in resultX)
        {
            Console.Write(diffX + " ");
        }
        Console.WriteLine();

        Console.WriteLine("Differences in y values:");
        foreach (var diffY in resultY)
        {
            Console.Write(diffY + " ");
        }
        Console.WriteLine();
    }
}

 

 

resultX, resultY 배열 이중 for문으로 곱해서 모든 곱 값 가져오기, 모든 곱 값 중에서 최대값, 최소값 출력하기

using System;

class Program
{
    static void Main()
    {
        // 첫째 줄 읽기
        string[] firstLine = Console.ReadLine().Split(' ');
        int n = int.Parse(firstLine[0]);
        int m = int.Parse(firstLine[1]);
        int k = int.Parse(firstLine[2]);

        // x와 y를 저장할 배열 생성
        int[] xArray = new int[k];
        int[] yArray = new int[k];

        // 둘째 줄부터 마지막 줄까지 읽기
        for (int i = 0; i < k; i++)
        {
            string[] coordinates = Console.ReadLine().Split(' ');
            int x = int.Parse(coordinates[0]);
            int y = int.Parse(coordinates[1]);

            // x와 y 값을 배열에 저장
            xArray[i] = x;
            yArray[i] = y;
        }

        // 배열 정렬
        Array.Sort(xArray);
        Array.Sort(yArray);

        // resultX와 resultY 배열 초기화
        int[] resultX = new int[k - 1];
        int[] resultY = new int[k - 1];

        // x와 y 배열의 인접한 수의 차이를 저장
        for (int i = 0; i < k - 1; i++)
        {
            resultX[i] = xArray[i + 1] - xArray[i];
            resultY[i] = yArray[i + 1] - yArray[i];
        }

        // resultX와 resultY 배열 출력
        Console.WriteLine("Differences in x values:");
        foreach (var diffX in resultX)
        {
            Console.Write(diffX + " ");
        }
        Console.WriteLine();

        Console.WriteLine("Differences in y values:");
        foreach (var diffY in resultY)
        {
            Console.Write(diffY + " ");
        }
        Console.WriteLine();

        // resultX와 resultY의 인덱스별 곱한 결과를 저장할 배열 초기화
        int[] multipliedResults = new int[(k - 1) * (k - 1)];

        // resultX와 resultY의 모든 인덱스를 곱해서 배열에 저장
        int index = 0;
        for (int i = 0; i < k - 1; i++)
        {
            for (int j = 0; j < k - 1; j++)
            {
                multipliedResults[index] = resultX[i] * resultY[j];
                index++;
            }
        }

        // 최대값과 최소값 출력
        int maxResult = int.MinValue;
        int minResult = int.MaxValue;

        foreach (var result in multipliedResults)
        {
            maxResult = Math.Max(maxResult, result);
            minResult = Math.Min(minResult, result);
        }

        Console.WriteLine($"Maximum result: {maxResult}");
        Console.WriteLine($"Minimum result: {minResult}");
    }
}

 

 

인접한 수의 차이를 새로운 배열에 저장할 때 가장 앞의 인덱스는 resultX[0] = xArray[0] - 0이, 가장 끝의 인덱스는 resultX[k] = m - xArray[k-1]이 들어가야 한다. 해당 부분 추가.

using System;

class Program
{
    public static void Main()
    {
        // 첫째 줄 읽기
        string[] firstLine = Console.ReadLine().Split(' ');
        int n = int.Parse(firstLine[0]);
        int m = int.Parse(firstLine[1]);
        int k = int.Parse(firstLine[2]);

        // x와 y를 저장할 배열 생성. k번 자를 때 k 개수 만큼 들어갈 배열.
        int[] xArray = new int[k];
        int[] yArray = new int[k];

        // 둘째 줄부터 마지막 줄까지 읽기
        for (int i = 0; i < k; i++)
        {
            string[] coordinates = Console.ReadLine().Split(' ');
            int x = int.Parse(coordinates[0]);
            int y = int.Parse(coordinates[1]);

            // x와 y 값을 배열에 저장
            xArray[i] = x;
            yArray[i] = y;
        }

        // 배열 정렬
        Array.Sort(xArray);
        Array.Sort(yArray);
        Console.WriteLine("xArray: ");
        foreach (var arrX in xArray)
        {
            Console.Write(arrX + " ");
        }
        Console.WriteLine();
        Console.WriteLine("yArray: ");
        foreach (var arrY in yArray)
        {
            Console.Write(arrY + " ");
        }
        Console.WriteLine();

        // resultX와 resultY 배열 초기화. 자른 수는 k, 잘라진 수는 k+1 이다.
        int[] resultX = new int[k + 1];
        int[] resultY = new int[k + 1];

        //resultX, resultY 배열의 첫 인덱스는 xArray[0] - 0 이기 때문에 그대로 xArray[0]이 들어가도 된다.
        resultX[0] = xArray[0];
        resultY[0] = yArray[0];

        // x와 y 배열의 인접한 수의 차이를 저장
        for (int i = 0; i < k - 1; i++)
        {
            resultX[i + 1] = xArray[i + 1] - xArray[i];
            resultY[i + 1] = yArray[i + 1] - yArray[i];
        }

        //resultX, resultY 배열의 마지막 인덱스는 전체 사각형 길이에서 xArray, yArray 마지막 인덱스를 뺀 값이다.
        resultX[k] = m - xArray[k - 1];
        resultY[k] = n - yArray[k - 1];

        // resultX와 resultY 배열 출력
        Console.WriteLine("Differences in x values:");
        foreach (var diffX in resultX)
        {
            Console.Write(diffX + " ");
        }
        Console.WriteLine();

        Console.WriteLine("Differences in y values:");
        foreach (var diffY in resultY)
        {
            Console.Write(diffY + " ");
        }
        Console.WriteLine();

        // resultX와 resultY의 인덱스별 곱한 결과를 저장할 배열 초기화. 배열의 크기는 (k + 1) * (k + 1)
        int[] multipliedResults = new int[(k + 1) * (k + 1)];

        // resultX와 resultY의 모든 인덱스를 곱해서 배열에 저장
        int index = 0;
        for (int i = 0; i < k + 1; i++)
        {
            for (int j = 0; j < k + 1; j++)
            {
                multipliedResults[index] = resultX[i] * resultY[j];
                index++;
            }
        }

        // 최대값과 최소값 출력
        int maxResult = int.MinValue;
        int minResult = int.MaxValue;

        foreach (var result in multipliedResults)
        {
            maxResult = Math.Max(maxResult, result);
            minResult = Math.Min(minResult, result);
        }

        Console.WriteLine($"Maximum result: {maxResult}");
        Console.WriteLine($"Minimum result: {minResult}");
    }
}

 

실행하면,

//input
10 12 2
3 8
9 3

 

//input
10 12 3
3 8
9 3
6 1

결과값이 잘 출력된다.

 

 


 

 

Q3. 주어진 알파벳의 나열에서 특정 구간의 최대 빈도 알파벳 구하기

각 구간 사이에 가장 많은 알파벳 찾기, 같으면 낮은 알파벳 출력

//input
30 5
AAAEKFMBBBKALDDFJSCCCVOZAAFLDD
11 12
7 24
12 23
13 27
1 19

 

A.

using System;
using System.Collections.Generic;
using System.Linq;

class Program
{
    static void Main()
    {
        // Read the input values
        string[] sizes = Console.ReadLine().Split(' ');
        int size = int.Parse(sizes[0]);
        int repeatCount = int.Parse(sizes[1]);

        string alphabetSequence = Console.ReadLine();

        // Handle each interval
        for (int i = 0; i < repeatCount; i++)
        {
            string[] interval = Console.ReadLine().Split(' ');
            int start = int.Parse(interval[0]) - 1; // 인덱스 조정을 위한 -1
            int end = int.Parse(interval[1]) - 1; // 인덱스 조정을 위한 -1

            // Count the frequencies within the interval
            Dictionary<char, int> intervalFrequency = new Dictionary<char, int>();

            for (int j = start; j <= end; j++)
            {
                char currentChar = alphabetSequence[j];

                if (!intervalFrequency.ContainsKey(currentChar))
                {
                    intervalFrequency[currentChar] = 1;
                }
                else
                {
                    intervalFrequency[currentChar]++;
                }
            }

            // Find the most frequently occurring alphabet within the interval
            char mostFrequent = intervalFrequency
                .OrderByDescending(pair => pair.Value) //pair.Value 기준으로 내림차순 정렬
                .ThenBy(pair => pair.Key) //빈도수가 같다면 pair.Key 기준 오름차순 정렬
                .First().Key; //정렬된 시퀀스에서 첫 번째 요소를 선택하고 그 키 값을 반환

            Console.WriteLine(mostFrequent);
        }
    }
}

위의 코드는 특정 구간을 입력할 때마다 결과 값이 나오고,

 

 

아래의 코드는 모든 기능은 같지만 모든 결과 값을 배열에 저장했다가 마지막에 한꺼번에 출력하는 코드이다.

using System;
using System.Collections.Generic;
using System.Linq;

class Program
{
    static void Main()
    {
        // Read the input values
        string[] sizes = Console.ReadLine().Split(' ');
        int size = int.Parse(sizes[0]);
        int repeatCount = int.Parse(sizes[1]);

        string alphabetSequence = Console.ReadLine();
        
        // 배열을 사용하여 결과 값을 저장
        char[] results = new char[repeatCount];

        // Handle each interval
        for (int i = 0; i < repeatCount; i++)
        {
            string[] interval = Console.ReadLine().Split(' ');
            int start = int.Parse(interval[0]) - 1; // 인덱스 조정을 위한 -1
            int end = int.Parse(interval[1]) - 1; // 인덱스 조정을 위한 -1

            // Count the frequencies within the interval
            Dictionary<char, int> intervalFrequency = new Dictionary<char, int>();

            for (int j = start; j <= end; j++)
            {
                char currentChar = alphabetSequence[j];

                if (!intervalFrequency.ContainsKey(currentChar))
                {
                    intervalFrequency[currentChar] = 1;
                }
                else
                {
                    intervalFrequency[currentChar]++;
                }
            }

            // Find the most frequently occurring alphabet within the interval
            char mostFrequent = intervalFrequency
                .OrderByDescending(pair => pair.Value) //pair.Value 기준으로 내림차순 정렬
                .ThenBy(pair => pair.Key) //빈도수가 같다면 pair.Key 기준 오름차순 정렬
                .First().Key; //정렬된 시퀀스에서 첫 번째 요소를 선택하고 그 키 값을 반환
            
            // 결과 값을 배열에 저장
            results[i] = mostFrequent;
        }
        // 배열에 저장된 결과 값을 한 줄 씩 출력
        foreach (char result in results)
        {
            Console.WriteLine(result);
        }
    }
}

728x90
반응형