프로그램(C# etc.)

배열에 A, B, C가 섞여 있는데, C, B, A 순서로 우선순위가 있다. 배열에서 가장 낮은 우선순위가 포함되어 있다면, 그 값을 리턴하는 c#코드 짜줘

질문폭격 2022. 12. 26. 14:29

Q1> 배열에 A, B, C가 섞여 있는데, C, B, A 순서로 우선순위가 있다. 배열에서 가장 낮은 우선순위가 포함되어 있다면, 그 값을 리턴하는 c#코드 짜줘

 

아래와 같은 코드를 작성할 수 있습니다.

string[] arr = { "A", "B", "C" };

string GetLowestPriority(string[] arr)
{
    if (arr.Contains("A"))
    {
        return "A";
    }
    else if (arr.Contains("B"))
    {
        return "B";
    }
    else if (arr.Contains("C"))
    {
        return "C";
    }
    else
    {
        return "No value with low priority found";
    }
}

string lowestPriority = GetLowestPriority(arr);
Console.WriteLine(lowestPriority);

 이 코드는 arr 배열에 "A"가 포함되어 있다면 "A"를, "B"가 포함되어 있다면 "B"를, "C"가 포함되어 있다면 "C"를, 아무것도 포함되어 있지 않다면 "No value with low priority found"를 리턴합니다.

참고: string.Contains(string value) 메서드는 지정된 문자열이 현재 문자열에 포함되어 있는지 여부를 나타내는 bool 값을 리턴합니다.

 

Q2> 배열에 A, B, C가 섞여 있는데, C, B, A 순서로 우선순위가 있다. 배열에서 가장 낮은 우선순위가 포함되어 있다면, 그 값을 리턴하는 검증코드 짜줘

string[] arr1 = { "C", "A", "B" };
string[] arr2 = { "A", "C", "B" };
string[] arr3 = { "B", "C", "A" };
string[] arr4 = { "B", "A", "C" };
string[] arr5 = { "A", "B", "C" };
string[] arr6 = { "C", "B", "A" };

string expected1 = "A";
string expected2 = "A";
string expected3 = "B";
string expected4 = "B";
string expected5 = "A";
string expected6 = "C";

string actual1 = GetLowestPriority(arr1);
string actual2 = GetLowestPriority(arr2);
string actual3 = GetLowestPriority(arr3);
string actual4 = GetLowestPriority(arr4);
string actual5 = GetLowestPriority(arr5);
string actual6 = GetLowestPriority(arr6);

Debug.Assert(expected1 == actual1);
Debug.Assert(expected2 == actual2);
Debug.Assert(expected3 == actual3);
Debug.Assert(expected4 == actual4);
Debug.Assert(expected5 == actual5);
Debug.Assert(expected6 == actual6);

Console.WriteLine("All tests passed");

 이 검증 코드는 총 6개의 테스트 케이스를 실행합니다. 각 테스트 케이스는 GetLowestPriority 함수가 올바른 값을 리턴하는지 검증합니다. 이 코드를 실행하면 "All tests passed"가 출력되면 테스트가 성공한 것입니다.

참고: Debug.Assert 메서드는 지정된 조건이 참이면 아무 작업도 하지 않고, 거짓이면 예외를 throw 합니다. 이 메서드는 일반적으로 개발과 테스트 시