[C#] 배열 조작

 프로그래머스 코딩 기초 트레이닝 - C# : 문자열 출력하기


- num_list 에 대한 제약 사항
- 배열 슬라이싱 및 복제 필요

풀이) 배열 원소 복제
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
using System;
 
public class Solution {
    public int[] solution(int[] num_list, int n) {
        /*
        2<= num_list의 길이 <= 30
        1<= num_list의 원소 <= 9
        1<= n <= num_list의 길이
        */
        if((num_list.Length >=2 && num_list.Length <=30&& (num_list.Length >= n && n>=1&& (Array.Find(num_list, e => e < 1 && e>9== 0 )){
            int[] answer = new int[n]; // n개 만큼 빈 array 생성
        
            for(int i = 0; i<n; i++)  // index 상 n 이전 까지의 값 복제
                answer[i] = num_list[i];
            
            return answer;
        }else
            return num_list; // 조건에 부합하는 array가 아닌경우 원본의 array를 
    }
}
cs


풀이)Linq 표현식 사용(num_list에 대한 제약은 제외)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
using System;
using System.Linq;
 
public class Solution {
    public int[] solution(int[] num_list, int n) {
        int[] answer = new int[]{};
        
        //인덱스 상 n 까지의 원소 복제 및 array 
        answer = num_list.Take(n).ToArray();
            
        return answer;
       
    }
}
cs
분석) 빈 배열 생성 후 Linq 표현식을 이용하여 새 값을 참조함

댓글