상세 컨텐츠

본문 제목

5명씩

코딩테스트/C#

by MJ_119 2024. 6. 16. 02:27

본문

문제 설명

최대 5명씩 탑승가능한 놀이기구를 타기 위해 줄을 서있는 사람들의 이름이 담긴 문자열 리스트 names가 주어질 때, 앞에서 부터 5명씩 묶은 그룹의 가장 앞에 서있는 사람들의 이름을 담은 리스트를 return하도록 solution 함수를 완성해주세요. 마지막 그룹이 5명이 되지 않더라도 가장 앞에 있는 사람의 이름을 포함합니다.


제한사항
  • 5 ≤ names의 길이 ≤ 30
  • 1 ≤ names의 원소의 길이 ≤ 10
  • names의 원소는 영어 알파벳 소문자로만 이루어져 있습니다.

입출력 예
using System;

public class Solution {
    public string[] solution(string[] names) {
        string[] answer = new string[(names.Length + 4) / 5];
        Console.Write(answer.Length);
        
        int a = 0;
        
        for(int i = 0; i < names.Length; i += 5)
        {
            answer[a] = names[i];
            a++;
        }
        
        return answer;
    }
}

 

다른 풀이

using System;

public class Solution {
    public string[] solution(string[] names) {
        int count = names.Length % 5 == 0 ? names.Length/5 : names.Length/5+1;
        string[] answer = new string[count];
        for(int i=0; i<count; i++)
        {
            answer[i] = names[i*5];
        }
        return answer;
    }
}

 

using System;
using System.Collections.Generic;

public class Solution {
    public string[] solution(string[] names) {
        List<string> list = new List<string>();

        for(int i = 0; i < names.Length; i+=5)
        {
            list.Add(names[i]);
        }
        return list.ToArray();
    }
}

'코딩테스트 > C#' 카테고리의 다른 글

n개 간격의 원소들  (0) 2024.06.17
n 번째 원소까지  (1) 2024.06.17
홀수 vs 짝수  (1) 2024.06.16
n 번째 원소부터  (0) 2024.06.16
l로 만들기  (0) 2024.06.13

관련글 더보기